[Fixed]-Django model get duplicated from foreignkey model

1👍

When you order by the related field votes, this causes Django to do a left outer join. If a title is related to multiple votes, it is returned in the queryset once for each vote.

Note that saving the votes is not creating duplicates. You can confirm this by ordering by a different field, and checking the count. As you say in your question, the primary key of the duplicates is the same, so you have not created extra titles in the database, the queryset is just returning the same titles multiple times.

Title.objects.order_by('pk').count()

To order by the number of votes, you need to annotate the queryset with the number of votes, then order by the annotation:

Title.objects.annotate(num_votes=Count('votes')).order_by('num_votes')

0👍

You can try to replace:


vote = Vote.objects.create(title=title, user=user)

to


vote, created = Vote.objects.get_or_create(title=title, user=user)

0👍

the probleme was coming from my title models :

class Title(GenericModel):
    """
    Model for title suggested by user
    """
    class Meta:
        ordering = ['votes']

    text = models.CharField(_('text'), max_length=255)

    artwork = models.ForeignKey(Artwork, blank=True,    related_name='titles')

    user = models.ForeignKey(ArtLover, blank=True)

    def __str__(self):
        return self.text

the ordering in meta was duplicating the model everytime i vote why is this happening? and how im suppose to order my title by the number of vote they get ?

Leave a comment