Django JOIN query without foreign key

前端 未结 3 1687
失恋的感觉
失恋的感觉 2021-02-20 10:37

Is there a way in Django to write a query using the ORM, not raw SQL that allows you to JOIN on another table without there being a foreign key? Looking through the documentatio

3条回答
  •  既然无缘
    2021-02-20 11:17

    The Django ForeignKey is different from SQL ForeignKey. Django ForeignKey just represent a relation, it can specify whether to use database constraints.

    Try this:

    request_url = models.ForeignKey(UserActivityLink, to_field='url_description', null=True, on_delete=models.SET_NULL, db_constraint=False)
    

    Note that the db_constraint=False is required, without it Django will build a SQL like:

    ALTER TABLE `user_activity` ADD CONSTRAINT `xxx` FOREIGN KEY (`request_url`) REFERENCES `user_activity_link` (`url_description`);" 
    

    I met the same problem, after a lot of research, I found the above method.

    Hope it helps.

提交回复
热议问题