0

I have two models. One represents several groups, and the other represents people in those groups with a ranking. I would like to have a field in the groups model that represents the highest ranked person inside that group. Is this possible?

For example:

Groups:
id  name    highest
1   alpha    gold    
2   bravo   diamond  

People:
name   group  rank
Dave     1    silver
bob      1    gold
dilan    1    silver
arthur   2    gold
mark     2    diamond
motionsickness
  • 157
  • 1
  • 2
  • 10

1 Answers1

1

I would like to have a field in the groups model that represents the highest ranked person inside that group.

In this case, you might want to add a ForeignKey to your Group model. What a foreign key does is it links one of the fields (which you can name it whatever you want) to another model class, which in your case, will be the User model.

But seeing as you want the highest ranked person, all the above actions will deem unrealistic as every time the leaderboard changes you need to refresh your model, and that's inconvenient.

What I'll suggest, instead of adding another field, is to render all the person objects and pass it as a part of the context. That way, as the user's rank changes, you don't need to refresh your model. Please refer to the doc's detail on passing context to view and a way to sort your data.

crimsonpython24
  • 2,223
  • 2
  • 11
  • 27
  • that was going to be my go-to in case there was no DB way to do it.I'll give it a bit more time before closing. Thank you for your suggestion. – motionsickness Jul 14 '20 at 11:53
  • What I will suggest is that, once a user is added/modified, you call a function that will re-sort the user list based on their rank. Then you can apply the update to the database (but still don't forget to create a foreign key object to store the user and pass in `None=true` as you most likely won't have an initial value). – crimsonpython24 Jul 14 '20 at 11:59