是否可以通过指定 ID 名称在没有外键的表上应用连接?

is it possible to apply join on tables which do not have foreign key, by specifying the id name?

我有一个没有外键约束的预制数据库。 我想知道我们是否可以在没有外键的情况下在 django ORM 中应用连接(我知道这不是最佳实践,但由于其预制模式,我无法更改它)。

我查了一下,但没有找到符合我要求的解决方案。 我尝试了以下,

https://books.agiliq.com/projects/django-orm-cookbook/en/latest/join.html

Join over django models

https://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/

https://www.quora.com/How-do-I-join-tables-in-Django

我有 表 1

TId = models.BigIntegerField(primary_key=True)
    field1 = models.FloatField(null=True, blank=True, default=None)
    field2 = models.CharField(max_length=10, default=None)
    field3 = models.CharField(max_length=10, default=None)
    field4 = models.CharField(max_length=10, default=None)

和表 2,

SId = models.BigIntegerField(primary_key=True)
    field5 = models.FloatField(null=True, blank=True, default=None)
    field6 = models.CharField(max_length=10, default=None)
    field7 = models.CharField(max_length=10, default=None)
    field8 = models.CharField(max_length=10, default=None)

我希望查询是,

select t1.field1, t1.field2, t2.field5 from table1 t1 inner/outer/left/right join table2 t2 on t1.TId = t2.SId 
where t2.field7 = "value";

Django 不关心外键约束。您仍然可以将您的字段声明为外键。

例如:

class Table2(models.Model):
    SId = models.OneToOneField('Table1', primary_key=True, db_column='SId')
    ...

现在您可以:

Table2.objects.filter(field7='value').values_list('SId__field1', 'SId__field2', 'field5')