1

The question is simple. im building a recipe website with multiple users to submit their recipes. i want to build one page listing all the users and arrange the user hierarchy based on their latest post. what is the best way to query the users in the views.py and pass to the context?

the code snippet is something like this;

models.py

class UserRecipe(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=200)
    created_date = models.DateTimeField(default=timezone.now)

as you can see the UserRecipe model linked to user using ForeignKey. So im building a view in views.py to list users and rank them based on the date of their last UserRecipe created_date.

so in order to query users and arrange them based on their UserRecipe created_date what is the best way to do it?

Arekay
  • 15
  • 5
  • Do you want to list all the recipes from newest to oldest? Or do you want to list the users, based on which user has most recently posted a recipe? – kujosHeist Nov 26 '17 at 23:55
  • i want to list the users based on which user has most recently post a recipe – Arekay Nov 27 '17 at 00:03
  • @Arekay in your filter query add ```order_by('-time_create')```. – Manoj Jadhav Nov 27 '17 at 00:18
  • See [this question](https://stackoverflow.com/questions/13757195/sort-django-queryset-by-latest-instance-of-a-subset-of-related-model) – Selcuk Nov 27 '17 at 00:42
  • @ManojJadhav that is ok if i want to order the UserRecipe itself but right now i want to order the users instead with their latest UserRecipe created_date – Arekay Nov 27 '17 at 01:15

1 Answers1

1

You can use the following query

users = User.objects.order_by("-userrecipe__created_date") 

It will be in the correct order, however there will be duplicates, i.e. there will be a user entry for each recipe they have created

If you are using postgres as your db you can avoid this by adding .distinct() to the end of the query, otherwise you can remove duplicates like this:

already_seen = []
for u in users:
    if u not in already_seen:
        already_seen.append(u)

users = already_seen
kujosHeist
  • 810
  • 1
  • 11
  • 25
  • thanks, im still in drafting mode, so im still using sqlite3 for db. distinct() doesnt work. so your already_seen solutions is good enough for me now. – Arekay Nov 27 '17 at 01:42