Django获取所有关系 [英] Django fetch all relations

查看:92
本文介绍了Django获取所有关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与该代码段结构相似的应用程序

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?

我考虑过为Blog模型创建一个管理器,该管理器可以获取该Blog的所有类别,但是它是对模型名称进行硬编码的

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)

有什么建议吗?

推荐答案

您想要的是选择相关.它返回一个QuerySet,它将自动遵循"外键关系,并在执行查询时选择该附加的相关对象数据.您对Blog的查询应类似于:

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 )

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

这篇关于Django获取所有关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆