Note that it was difficult to find information on Left outer join in Django's ORM.
I often use select_related ()
and prefetch_related ()
to pull items that the model specifies as foreign keys.
class User(models.Model):
name = models.CharField()
class Comment(models.Model):
user = models.ForeignKey(User, null=True)
content = models.CharField()
For example, if such a model is defined, it can be pulled as follows.
comment = Comment.objects.select_related().first()
print(comment.user.name)
It seems that reverse lookup is possible if only one data is used as a reference.
comments = User.objects.get(pk=1).comment_set.all()
# id=You can extract a comment that holds 1 User
If you do something like ↑, you'll find that Django joins are mostly Inner joins. What do you do with outer join after starting to operate the aggregation system? It will be.
comments = Comment.objects.filter(user__isnull=True)
That's right.
I checked it once but forgot it, so I wrote it down.
It is important that the items are declared with models.ForeignKey ()
to combine.
(Otherwise you can't do something like comment.user.name)
Recommended Posts