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)
- Ember serializer customization for alternate url
- Upload images before form submit Django
- Including template that is located outside of the main folder
- Django. How to show and hide DIV based on the selection of the dropdown menu?
- Django-registration-redux is not working
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 ?
- Dynamic files across Heroku dynos
- How to query articles a user has commented on?
- Not able to serve media files in django
- Pycharm can't find haystack but terminal can