Django fetch all relations

时光怂恿深爱的人放手 提交于 2019-12-25 05:04:23

问题


I have an app with a similar structure as this snippet

class Blog(models.Model):
    name = models.CharField(max_length=25)

class Category(models.Model):
    name = models.CharField(max_length=25)
    blog = models.ForeignKey(Blog)

class Entry(models.Model):
    title = models.CharField(max_length=25)
    category = models.ForeignKey(Category)

What is the most generic way, that i will be able to use in other apps to fetch all blogs with their category and entries?

I thought about creating a manager for the Blog model, that can fetch all the Categories for that blog, but it's hardcoding the model names

 class BlogManager(models.Manager):
     def categories(self):
         return Category.objects.filter(blog=self)

Any suggestions?


回答1:


What you want is a Select Related. It returns a QuerySet that will automatically "follow" foreign-key relationships, selecting that additional related-object data when it executes its query. Your query for Blogs would look something like:

Blog.objects.select_related().filter( something )

or

Blog.objects.select_related().get( something )



回答2:


Why not use a standard way? Filter using Blog's PK with FK relation.

Category.objects.filter(blog__pk=self.pk)


来源:https://stackoverflow.com/questions/10909265/django-fetch-all-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!