Chen Triều
Chen Triều

Reputation: 79

ModelViewset in django

I'm newbie of Django Rest-framework. I use Modelviewset to create API for project. I want to get list of thing not by id and i use lookup_field to do that. But it is only return 1 object. How can i custom it to return multible object?

this is my model

class Rating(models.Model):
    dayandtime = models.DateTimeField(auto_now_add=True)
    ratingpoint = models.IntegerField(null=True,blank=True)
    ratingcomment = models.TextField(null=True, blank=True)
    img = models.ImageField(upload_to='static',default=None)
    product = models.ForeignKey(Product,on_delete=models.CASCADE)
    user = models.ForeignKey(User,on_delete=models.CASCADE)

This is my views

class RatingViewSet(viewsets.ModelViewSet):
    queryset = Rating.objects.all()
    serializer_class = RatingSerializer
    lookup_field = "product"

This is my Serializer

class RatingSerializer(ModelSerializer):
    class Meta:
        model=Rating
        fields=["id","dayandtime","ratingpoint", "ratingcomment","img","product","user"]
        lookup_field = "product" 

Please help me to sovle this problem. Thank you very much

Upvotes: 1

Views: 1844

Answers (1)

Rvector
Rvector

Reputation: 2442

You want to use filter on the api and return multiple objects. But lookup_field is used to for performing object lookup of individual model instances. There are many way to achieve your goal, but i'll show you filter by query parameters.

You can override get_queryset() to deal with URLs such as http://yourdoamin.com/api/ratings?product=1 ( here we assume that you want to filter by product id ).

class RatingViewSet(viewsets.ModelViewSet):
    serializer_class = RatingSerializer

    def get_queryset(self):
        queryset = Rating.objects.all()
        product= self.request.query_params.get('product')
        if product not None:
            queryset = queryset.filter(product_id=product)
        return queryset

Of course, you can add many if/elif/else block to handle many query parameters.

You can also use a similar method : The SearchFilter class to achieve the same goal.

More info on the DRF filtering documentation

Upvotes: 2

Related Questions