[英]django model select_related or prefetch_related child model
[英]prefetch_related with Django 1.5 + django-model-utils
我有一个与以下类似的模型,并且我使用的是django-model-utils提供的InheritanceManager,它使我可以查询所有子类(在这种情况下,无论TextPost还是PhotoPost,我都会得到所有帖子)。
在类似情况下,如何在PhotoPosts的照片和TextPost的身体上使用prefetch_related进行查询?
用django-model-utils查询看起来像这样:
Post.objects.filter(user=user).select_subclasses()
-
class Post(models.Model):
post_type = models.ForeignKey(ContentType)
user = models.ForeignKey(User, blank=True, null=True, related_name='posts')
objects = InheritanceManager()
class Meta:
app_label = 'posts'
def save(self, *args, **kwargs):
if not self.pk:
self.post_type = ContentType.objects.get_for_model(type(self))
# import pdb; pdb.set_trace()
super(Post, self).save(*args, **kwargs)
class TextPost(Post):
""" Text post model """
body = models.TextField()
class Meta:
app_label = 'posts'
class PhotoPost(Post):
""" Photo post model """
photo = models.ForeignKey('posts.Photo')
class Meta:
app_label = 'posts'
您可以使用prefetch_related方法来收集此信息。
Post.objects.filter(user=user).select_subclasses().prefetch_related('photo','body')
正如Andy正确指出的那样,您可以使用prefetch_related方法来收集此信息。 但是,查询略有不同。 您必须预取related_name(在使用模型继承时是隐藏的)。 另外,TextPost的主体只是文本字段,因此您无需预取它,这由select_subclasses照顾
Post.objects.filter(user=user)\
.select_subclasses()\
.prefetch_related('photopost__photo')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.