我有一个类似于以下的模型,并且我正在使用 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'