简体   繁体   中英

Querying for related sets of objects in Django models

Assume that I've following classes in my model:

class User(BaseModel):
  ..

class Node(BaseModel):
  ..
  author = models.ForeignKey(User, related_name='%(class)ss')
  tags   = models.ManyToManyField('Tag', related_name='%(class)ss')
  ..

class Tag(BaseModel):
  ..

And now, I'd like to have a method in a User class, which would return all tags for the user's node:

class User(BaseModel):
  ..
  def get_tags(self):

    # Here some more querying for tags in selected nodes
    user_tags = self.nodes.filter(author=self) # What to add if possible?

    return ..

I'd like the user_tag collection to include all tags that were used in nodes that has been authored by a given user. How to achieve this without custom SQL?

If have got your question correctly,this should do it,select_related() method recursively prepopulates the cache of all one-to-many relationships ahead of time.

More details click here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM