0
我正在用Django Rest框架構建一個應用程序。使用uid(username,userId)的Django Rest框架查詢
這裏是我的Django模型:
class Location(models.Model):
uid = models.ForeignKey('auth.User', related_name='locations', unique=True, on_delete=models.CASCADE)
area = models.IntegerField(choices=AREA, default=0)
address = models.TextField(max_length=150)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('created_at',)
verbose_name = 'Location'
verbose_name_plural = 'Locations'
def __str__(self):
return self.area
我的串行:
class LocationSerializer(serializers.ModelSerializer):
# owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Location
fields = '__all__'
我的觀點:
class LocationViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list` and `detail` actions.
"""
queryset = Location.objects.all()
serializer_class = LocationSerializer
permission_classes = (permissions.IsAuthenticated, permissions.IsAdminUser,)
我的路線是註冊使用router.register
router = DefaultRouter()
router.register(r'locations', views.LocationViewSet)
當我這樣查詢:localhost:8000/locations/<locationId>
我得到特定位置匹配位置id的結果。但我想用這樣的用戶名/ ID查詢: 。我怎樣才能做到這一點?
P.S .:我是Django的新手。
如果你想工作'地點/','地點/ ','locations/uid'比你的API設計差。資源應該只有一個ID。使用查詢參數'location?user_id = '或使其他資源位置/用戶/ '。 [此鏈接](http://restful-api-design.readthedocs.io/en/latest/resources.html)可以提供幫助。 –
Raz