Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

317
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda