0

Django Restフレームワークでアプリケーションを構築しています。Django Restフレームワーククエリ(ユーザ名、ユーザID)

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) 
を使用して登録されている。ここ

は私のDjangoのモデルであり、

このようにクエリを実行すると:localhost:8000/locations/<locationId>私は特定の場所と一致する場所IDの結果を取得します。しかし、次のようにusername/idを使って質問したいと思います: ​​。どうすればこれを達成できますか?

P .:私はDjangoを初めて使いました。

+0

したい場合'locations/'、 'locations/'、 'locations/uid'はあなたが悪いAPI設計よりもうまく動作します。リソースはidを1つだけ持つ必要があります。クエリパラメータ 'locations?user_id = 'を使用するか、他のリソース 'location/user/'を作成してください。 [このリンク](http://restful-api-design.readthedocs.io/en/latest/resources.html)が役立ちます。 – Raz

答えて

1

私たちは、このようなhttp://example.com/api/purchases?username=denvercoder9ようなURLに対処し、ユーザ名パラメータがURLに含まれている場合にのみ、クエリセットをフィルタリングするために)(.get_querysetオーバーライドすることができます:Django REST frameworkドキュメントから

class PurchaseList(generics.ListAPIView): 
serializer_class = PurchaseSerializer 

def get_queryset(self): 
    """ 
    Optionally restricts the returned purchases to a given user, 
    by filtering against a `username` query parameter in the URL. 
    """ 
    queryset = Purchase.objects.all() 
    username = self.request.query_params.get('username', None) 
    if username is not None: 
     queryset = queryset.filter(purchaser__username=username) 
    return queryset 

関連する問題