LoginSignup
12
8

More than 5 years have passed since last update.

Django QuerySet 外部キー制約無しで結合する

Last updated at Posted at 2019-02-23

内部結合(直積した結果からユーザー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)
12
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
8