Django:查询多种类型的对象

时间:2013-09-13 00:10:45

标签: django django-models django-queryset

我有一个相当基本的模型,允许用户创建不同“类型”的帖子。目前有一种文本类型和一种照片类型,它继承自基础“Post”类型。

我正在拉TextPostsPhotoPosts并链接两个QuerySet,但这似乎是一个坏主意。

有没有办法一次只查询这两种类型的帖子?我在.filter()本身没有使用Post的原因是因为我(可能)没有办法从中获取TextPostPhotoPost对象(或者我呢?)

PS:如果我永远不会单独使用Post,那么将它称为BasePost或Post更有意义吗?

class Post(AutoDateTimeModel):
    POST_TYPES = (
        # Linkable Social Networks
        ('TEXT', 'Text'),
        ('PHOTO', 'Photo'),
        ('LINK', 'Link'),
    )

    post_type = models.ForeignKey(ContentType)
    user = models.ForeignKey(User, blank=True, null=True)
    interests = models.ManyToManyField(Interest, related_name='interests')

    class Meta:
        app_label = 'posts'
        ordering = ('-created_at',)

    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. This can contain multiple photos. """
    description = models.TextField()

    class Meta:
        app_label = 'posts'

class Photo(models.Model):
    """ Individual image model, used in photo posts. """
    caption = models.TextField()
    # source_url = models.URLField(blank=True, null=True)
    image = ImageField(upload_to=upload_to)
    post = models.ForeignKey(PhotoPost, blank=True, null=True, related_name='photos')
    user = models.ForeignKey(User, blank=True, null=True, related_name='photos')

    class Meta:
        app_label = 'posts'

    def __unicode__(self):
        return 'Photo Object by: ' + str(self.user.get_full_name())

1 个答案:

答案 0 :(得分:2)

您可以在Post类中使用InheritanceManager来使用这个不错的应用django-model-utils

来自文档的一个很好的例子:

from model_utils.managers import InheritanceManager

class Place(models.Model):
    # ...
    objects = InheritanceManager()

class Restaurant(Place):
    # ...

class Bar(Place):
    # ...

nearby_places = Place.objects.filter(location='here').select_subclasses()
for place in nearby_places:
    # "place" will automatically be an instance of Place, Restaurant, or Bar

申请你的情况:

class Post(AutoDateTimeModel):
    ...
    objects = InheritanceManager()


class TextPost(Post):
    ...

class PhotoPost(Post):
    ...

这回答了你的问题:有没有办法一次只查询两种类型的帖子?

您现在可以查询帖子,生成TextPost和Photoposts的实例