我有一个相当基本的模型,允许用户创建不同“类型”的帖子。当前有一个 Text 类型和一个 Photo 类型,它们继承自基本 ' Post
' 类型。
我目前正在拉动TextPosts
和PhotoPosts
链接两个 QuerySet,但这似乎是个坏主意。
有没有办法一次简单地查询两种类型的帖子?我不使用本身的原因.filter()
是Post
因为我(大概)没有任何方法可以从中获取TextPost
orPhotoPost
对象(或者我可以吗?)
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())