Django gets all related model entries

I have 3 models for to-do list application:

class Topic(models.model) user = models.ForeignKey(UserProfile) lists = models.ManyToManyField(List) class List(models.model) activities = models.ManyToManyField(Activity) class Activity(models.model) activity = models.CharField(max_length=250) 

This makes sense when the user selects a topic, then a list (subcategory) that shows all the actions in this list.

But how could I effectively request things like

  • All actions of user X (regardless of topic or list)
  • All actions on topic X for user X (regardless of lists)

Should I use select_related() in the query, and not a loop through related objects, or is there a more efficient way without a loop? (Or should I change my models?)

+6
source share
2 answers

Use the double-underscore syntax to query between relationships.

All actions for the user:

 Activity.objects.filter(list__topic__user=my_user) 

All actions for the user for the topic:

 Activity.objects.filter(list__topic=my_topic) 

(Note that currently the theme is for one user only. Not sure what this means: you are describing a user who selects a topic that cannot happen here. Potentially, the link from the topic in UserProfile should go a different way, or ManyToMany .)

+9
source

Give them related names (easier to manage):

 class Topic(models.model) user = models.ForeignKey(UserProfile, related_name = 'topics') lists = models.ManyToManyField(List, related_name = 'topics') class List(models.model) activities = models.ManyToManyField(Activity, related_name = 'lists') class Activity(models.model) activity = models.CharField(max_length=250) 

Then you can do awesome things:

 user = UserProfile.objects.get(pk=1) # for example user.topics.all() # returns all topics topic = Topic.objects.get(pk=1) # for example topic.users.get(pk=1) # returns user lists = topic.lists.all() # returns List object instances QuerySet for list in lists: list.activites.all() 

Useful information: https://docs.djangoproject.com/en/dev/ref/models/relations/

0
source

Source: https://habr.com/ru/post/959369/


All Articles