我有一个类似于以下内容的模型,并且我正在使用 django-model-utils 提供的 InheritanceManager,它允许我查询所有子类(在这种情况下,我会获取所有帖子,无论 TextPost 或 PhotoPost )。
类似的情况,如何通过 prefetch_lated 查询 PhotoPosts 的照片和 TextPost 的正文?
使用 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'
最佳答案
正如 Andy 正确指出的那样,您可以使用 prefetch_lated 方法来收集此信息。但是,查询略有不同。您必须预取相关名称(使用模型继承时,该名称是隐藏的)。另外,TextPost 的正文只是文本字段,因此您不需要预取它,这由 select_subclasses 处理
Post.objects.filter(user=user)\
.select_subclasses()\
.prefetch_related('photopost__photo')
关于python - prefetch_与 Django 1.5 + django-model-utils 相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19511368/