0

我有一个相当基本的模型,允许用户创建不同“类型”的帖子。当前有一个 Text 类型和一个 Photo 类型,它们继承自基本 ' Post' 类型。

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

有没有办法一次简单地查询两种类型的帖子?我不使用本身的原因.filter()Post因为我(大概)没有任何方法可以从中获取TextPostorPhotoPost对象(或者我可以吗?)

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())
4

1 回答 1

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 实例

于 2013-09-13T00:23:46.853 回答