我尝试使用django创建一个Web应用程序并连接到SQL Server数据库。我用来以django形式显示数据的表由2列组成。它们都是外键,并且它们都共同构成了表的主键
创建表[dbo]。[MyTable]([ID_Field1] [int]不为空, [ID_Field2] [int]不为空,约束[PK_Movies2Genres]主 集群([ID_Field1] ASC,[ID_Field2] ASC)与(PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON)ON [主])ON [PRIMARY]
ALTER TABLE [dbo]。[MyTable]带有检查添加约束[FK_Field2] 外键([ID_Field2])参考[dbo]。[表2]([ID_Field2])
ALTER TABLE [dbo]。[MyTable]检查约束[FK_Field2]
ALTER TABLE [dbo]。[MyTable]带有检查添加约束[FK_Field1] 外键([ID_Field1])参考[dbo]。[表1]([ID_Movie])
ALTER TABLE [dbo]。[MyTable]检查约束[FK_Field1]
现在,django显然无法创建与这种sql表结构相对应的模型,即,它无法创建由多个字段组成的主键。而是将主键设置在2列之一中,并在模型类的meta部分中设置
unique_together =((''id_field1','id_field2'),)
完整的模型:
MyTable(models.Model)类:
id_field1 = models.ForeignKey(Table1, on_delete=models.DO_NOTHING, db_column='ID_Field1') id_field2 = models.ForeignKey(Table2, on_delete=models.DO_NOTHING, db_column='ID_Field2') class Meta: managed = False db_table = 'MyTable' unique_together = (('id_field1', 'id_field2'),)
但是,这是django inspectdb告诉我要做的。我知道django在没有定义主键时会自动创建一个名为id的字段。尽管定义了主键,但这里似乎是这样。知道如何处理该问题吗?
答案 0 :(得分:1)
使用:https://github.com/onysos/django-composite-foreignkey
class Customer(models.Model):
company = models.IntegerField()
customer_id = models.IntegerField()
name = models.CharField(max_length=255)
address = CompositeForeignKey(Address, on_delete=CASCADE, to_fields={
"tiers_id": "customer_id",
"company": LocalFieldValue("company"),
"type_tiers": RawFieldValue("C")
})
class Meta(object):
unique_together = [
("company", "customer_id"),
]
class Contact(models.Model):
company_code = models.IntegerField()
customer_code = models.IntegerField()
surname = models.CharField(max_length=255)
# virtual field
customer = CompositeForeignKey(Customer, on_delete=CASCADE, related_name='contacts', to_fields={
"customer_id": "customer_code",
"company": "company_code"
})