Django ORM&复合主键。关系状况:“这很复杂。”

时间:2017-07-13 13:27:04

标签: python sql-server django django-orm

我有一个(遗留)数据库,包含以下表格。如何在Django的视图和模板中遵循从orders对象到delivery_adress的关系?

在SQL中,我只是在customer_fk = customer_fk和customer_fk = customer_fk上使用join delivery_adress,但它如何在Django ORM中运行?

这些表定义如下(我试图标记FK关系):

 orders
id | ordernr | product | amount | customer (FK) | delivery_adress (FK)
---+---------+---------+--------+---------------+---------------------
 1 | 20      | 5       | 200    | 1             | 1
 2 | 21      | 3       | 400    | 2             | 1
 3 | 22      | 2       | 20     | 2             | 2
 4 | 23      | 1       | 1      | 3             | 1
                                       |               |
 customer   ---------------------------                |
id | name  |----                                       |
---+-------+   |                                       |
 1 | John  |   |                                       |
 2 | Steve |   |                              ---------
 3 | Guy   |   |                             |
 4 | Joe   |   |                             |
               |                             |
 delivery_adress
customer (PK/FK) | delivery_adress(PK) | adress
-----------------+---------------------+-------
1                | 1                   | SF
2                | 1                   | LA
2                | 2                   | NY
3                | 1                   | CH

Model delivery_adress是:

class Delivery_adress(models.Model):
    customer= models.ForeignKey(Customer, models.DO_NOTHING, db_column='adresse', primary_key=True)
    delivery_adress = models.CharField(max_length=6, primary_key=True)
    #... other stuff ...

    class Meta:
        managed = False
        unique_together = (('customer', 'delivery_adress'),)

0 个答案:

没有答案