5๐
โ
I am trying to obtain a QuerySet that contains something similar:
| user | reward__count | | 1 | 103 | | 2 | 50 | | 3 | 67 |
This you can do, by using aggregations on the Reward
objects:
# Fetch a list of rewards, grouped by
rewards = Reward.objects.values('user').annotate(Count('id')).order_by()
This will give you a list like this:
[
{'user': 1, 'id__count': 103},
{'user': 2, 'id__count': 50},
{'user': 3, 'id__count': 67},
...
]
Where user
is the user ID, and id__count
is the number of rewards associated with that user.
๐คsolarissmoke
4๐
@solarissmoke has posted a good answer which I upvoted, I would like to propose an alternative? an unmanaged model.
Create an unmanaged model that points to the same table as the one in the untouchable library app.
class RewardOnSteroids(models.Model):
user = models.ForeignKey(User, related_name='pick something')
class Meta:
managed = False
db_table = 'original table name'
๐คe4c5
Source:stackexchange.com