Reputation: 153
I have the following 2 models:
class User(models.Model):
user_id = models.IntegerField(null=True)
name = models.CharField(max_length=50)
class Blog(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(User, null=True)
timestamp = models.DateTimeField()
How can I write a Django model query to get a list of objects which has the following formation -
[(user_object, number of blog posts of this user), ...]
This list is supposed to be in descending order. Basically, I want to obtain information about how many blog posts a user has written.
Incase, 2 users have the same number of blog posts, I want them to be sorted based on the latest timestamp of the blogpost created by them.
So, far I've tried the following and remained unsuccessful in my approaches.
user = User.objects.all()
serializer = UserSerializer(user, many=True)
user = list(serializer.data)
user_ranks = [(key, len(list(group))) for key, group in groupby(user)]
user_ranks = sorted(user_ranks, key=lambda x: x[1], reverse=True)
I do not know how to plug in the timestamp
comparison into the above mentioned code. Also, is there a better way of achieving this?
P.S: Number of entries in User
is same as number of entries in Blog
Upvotes: 0
Views: 80
Reputation: 966
if you set
user = models.ForeignKey(User, null=True, related_name='bloguser')
You can use
from django.db.models import Count
some_query = User.objects.filter( ... ).annotate( foobar = count('bloguser') )
to attach the number of blogs, which you can then access in your template via some_query.foobar.
for the time stamp
some_query = User.objects.filter( ... ).annotate( foobar = count('bloguser') ).annotate( foomax = Max('bloguser__timestamp') )
Upvotes: 1