Django: querying multiple types of objects
I have a fairly basic model that allows users to create posts of different
'types'. There's currently a Text type and a Photo type that inherits from
a base 'Post' type.
I'm currently pulling TextPosts and PhotoPosts and chaining the two
QuerySets, but this seems like a bad idea.
Is there a way to simply query for both types of posts at once? The reason
I'm not using .filter() on Post itself is because I (presumably) don't
have any way of getting the TextPost or PhotoPost object from it (or do
I?)
PS: Does it make more sense to call it BasePost or Post if I'll never be
using Post by itself?
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())
No comments:
Post a Comment