extract or return only the model instance of a foreign key or one to one field from a queryset in django
Sep
14
1
1
Lets say I have two models connected 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 want to run a query over all MagicalPost objects but I only want to receive the Post instances.
I can use the select_related() option which will only create one database call:
magical_posts = MagicalPost.objects.select_related('post') posts = [] for magical_post in magical_posts: posts.append(magical_post.post) return posts
Or I could use two queries which syntactically is simpler:
posts_ids = MagicalPost.objects.values_list('post', flat=True) posts = Post.objects.filter(id__in=posts_ids) return posts