0

I have database created by Django model, where idRecruteur is the fields of the table Offre.

I need to count the number of rows where idRecruteur = 1.

This is my "Offre" table code:

@python_2_unicode_compatible
class Offre(models.Model):          
    titre = models.CharField(max_length=100)
    dateAjout = models.DateField(auto_now=False, auto_now_add=False)
    nature = models.CharField(max_length=50)
    duree = models.CharField(max_length=50)
    niveau = models.CharField(max_length=50)
    description = models.CharField(max_length=50)
    salaire = models.FloatField(null=True, blank=True)
    idRecruteur = models.ForeignKey(Recruteur, related_name="Offre", on_delete=models.CASCADE)
    def __str__(self):
        return "Offre: {}".format(self.title)

and this is my queryset:

class OffresparEntrepriseViewSet(ModelViewSet):
    queryset = Offre.objects.filter(idRecruteur=1).count()
    serializer_class = OffreSerializer

I get the error " AttributeError: 'int' object has no attribute 'model' "

Any ideas what I am doing wrong?

ccr0x
  • 51
  • 5

1 Answers1

0

ViewSet's queryset attribute should be QuerySet object, but count() returns integer. You need to use queryset = Offre.objects.filter(idRecruteur=1) as viewset queryset, and move counting functionality to another level. For example using list_route:

class OffresparEntrepriseViewSet(ModelViewSet):
    queryset = Offre.objects.filter(idRecruteur=1)
    serializer_class = OffreSerializer

    @list_route()   
    def count(self, request):
        count = self.queryset.count()
        return Response({'count': count})

Now you can get count by accesing viewset_url/count url.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100