内部結合(直積した結果からユーザーIDが等しいもの)
Customer.objects.extra(
tables=['django_user'],
where=['customers.created_user_id=django_user.id']
).extra(select={'username': "django_user.last_name+django_user.first_name"})
SELECT (django_user.last_name+django_user.first_name) AS `username`,
`customers`.`id`,
`customers`.`created_at`,
`customers`.`created_user_id`
FROM `customers`,
`django_user`
WHERE (customers.created_user_id=django_user.id)
ORDER BY `customers`.`id` ASC
外部結合
https://stackoverflow.com/questions/21271835/left-join-django-orm
https://github.com/django/django/blob/master/django/db/models/sql/datastructures.py#L26-L139
joinField = ForeignKey(
to=User,
on_delete=lambda: x,
)
joinField.opts = Options(Customer._meta)
joinField.opts.model = Customer
joinField.get_joining_columns = lambda: (("created_user_id", "id"),)
j = Join(
User._meta.db_table,
Customer._meta.db_table,
'T1',
"LEFT JOIN",
joinField,
True
)
q = Customer.objects.values()
q = q.extra(select={'username': "django_user.last_name+django_user.first_name"})
q.query.join(j)
print(q.query)