开发者

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

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.开发者_JAVA百科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)


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.


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')


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜