Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

313
Views
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!