Django filter by number of ForeignKey and less than a month in DateField -
i have model this:
class moviehistory(models.model): watched_by = models.foreignkey(user) time = models.datetimefield(auto_now_add=true) movie = models.foreignkey(movie)
i want 15 movies watched in last 30 days. far have this:
movie.objects.filter(time__gte=datetime.now()-timedelta(days=30))
how filter again, , order them movie count? know can filter first 15 results this: [:15]
, don't know how order amount of movies in model, , pick 1 of each (so don't have repeated moviehistories same movies on each one).
thanks.
annotation best approach:
from django.db.models import count most_watched = movie.objects.all().annotate(num_watched = count('watched_by')).order_by('-num_watched')[:15]
i haven't tested this, believe on way answer. please let me know if works! may need replace count('watched_by')
count('watched_by_id')
or whatever field name in database (check ./manage.py sql your_appname
).
hope helps!
for more on using these annotations: https://docs.djangoproject.com/en/dev/topics/db/aggregation/#cheat-sheet
Comments
Post a Comment