How can I do INNER JOIN in Django in legacy database?

半腔热情 提交于 2020-01-04 05:23:32

问题


Sorry for probably simple question but I'm a newby in Django and really confused.

I have an ugly legacy tables that I can not change.
It has 2 tables:

class Salespersons(models.Model):
    id = models.IntegerField(unique=True, primary_key=True)
    xsin = models.IntegerField()
    name = models.CharField(max_length=200)
    surname = models.CharField(max_length=200)

class Store(models.Model):
    id = models.IntegerField(unique=True, primary_key=True)
    xsin = models.IntegerField()
    brand = models.CharField(max_length=200)

So I suppose I can not add Foreign keys in class definitions because they change the tables.

I need to execute such sql request:

SELECT * FROM Salespersons, Store INNER JOIN Store ON (Salespersons.xsin = Store.xsin);

How can I achieve it using Django ORM?
Or I'm allowed to get Salespersons and Store separately i.e.

stores = Store.objects.filter(xsin = 1000)
salespersons = Salespersons.objects.filter(xsin = 1000)

回答1:


Given your example query, are your tables actually named Salespersons/Store? Anyway, something like this should work:

results = Salespersons.objects.extra(tables=["Store"],
                          where=["""Salespersons.xsin = Store.xsin"""])

However, given the names of the tables/models it doesn't seem to me that an inner join would be logically correct. Unless you always have just 1 salesperson per store with same xsin.




回答2:


If you can make one of the xsin fields unique, you can use a ForeignKey with to_field to generate the inner join like this:

class Salespersons(models.Model):
    xsin = models.IntegerField(unique=True)

class Store(models.Model):
    xsin = models.ForeignKey(Salespersons, db_column='xsin', to_field='xsin')

>>> Store.objects.selected_related('xsin')



回答3:


I don't see why you can't use the models.ForeignKey fields even if the database lacks the constraints -- if you don't explicitly execute the SQL to change the database then the tables won't change. If you use a ForeignKey then you can use Salespersons.objects.select_related('xsin') to request that the related objects are fetched at the same time.



来源:https://stackoverflow.com/questions/5178215/how-can-i-do-inner-join-in-django-in-legacy-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!