Does anyone know if it's possible to extract only the model instances of a foreign key or one to one field from a queryset in Django?
Hypothetically lets say I have two classes, a Post and a MagicalPost, linked by a OneToOne Field like so:
class Post(models.Model):
...
class MagicalPost(models.Model):
post = models.OneToOneField('Post')
pony = models.TextField(max_length=100, help_text='This is where the MAGIC happens!')
I'd like to run a query on all magical posts, but I only want to receive the post objects. Right now I'm looping through the queryset in order to extract the posts:
magical_posts = MagicalPost.objects.all()
posts = []
for magical_post in magical_posts:
posts.append(magical_post.post)
return posts
Further down the line the posts get processed by functions that operate on general Post objects so I don't want to deal with the magical_post.post extrapolation, nor do I need the magical attributes.
This doesn't "feel" right. I'm thinking there could be a better way to extract the foreign keys, so if anyone knows of a better/cleaner way to do this I'm all ears; otherwise I'm just going to keep it li开发者_开发问答ke this because . . . well . . . it works!
Thanks.
You can easily use select_related
for example. It would be only one db query.
magical_posts = MagicalPost.objects.select_related()
# same code
Or use 2 queries like this:
posts_ids = MagicalPost.objects.values_list('post', flat=True)
posts = Post.objects.filter(id__in=posts_ids)
精彩评论