繁体   English   中英

Django中同一字段的多个外键

[英]Multiple ForeignKey to the same field in Django

我不能向同一个字段添加两个外键约束?

我对这种关系不是 100% 确定,所以我已经包括了这些表格。 希望它也可以帮助其他人学习 Django: Transaction

+----------+-----+---------------------+
|   guid   | plu |      datetime       |
+----------+-----+---------------------+
| 00003516 |   1 | 2015-09-22 12:11:12 |
| 0000386a |   2 | 2015-02-22 12:11:10 |
| 0000c59d |   2 | 2015-03-22 12:11:10 |
| 0000f03f |   3 | 2015-01-22 12:12:12 |
+----------+-----+---------------------+

普拉

+-----+------+
| plu | name |
+-----+------+
|   1 | aaa  |
|   2 | bbb  |
|   3 | ccc  |
+-----+------+

金融

+-----+------------+------------+-------+
| plu |    from    |     to     | price |
+-----+------------+------------+-------+
|   1 | 2013-01-22 | 2015-01-23 |    10 |
|   1 | 2015-01-23 | 2015-02-29 |    20 |
|   2 | 2013-01-22 | 2015-01-22 |    10 |
|   3 | 2013-01-22 | 2015-01-22 |    30 |
+-----+------------+------------+-------+

基于此,我创建了以下模型:财务

class Finance(models.Model):
    guid = models.AutoField(primary_key=True)
    from = models.DateField()
    to = models.DateField()
    price = models.DecimalField(max_digits=10, decimal_places=2)

逻辑单元

class Plu(models.Model):
    plu = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=200, null=True)

交易

class Transaction(models.Model):
    guid = models.CharField(primary_key=True, max_length=38)
    plu = models.ForeignKey(Plu, db_column='plu')
    finance = models.ForeignKey(Finance, db_column='plu')
    datetime = models.DateTimeField()

当我尝试运行它时,我收到以下错误 - 该怎么办?:

app.Transaction: (models.E007) Field 'finance' has column name 'plu' that is used by another field.
    HINT: Specify a 'db_column' for the field.

您已复制并粘贴并包含相同的 db_column 名称,您需要更改它

finance = models.ForeignKey(Finance, db_column='finance')

注意:您实际上根本不需要指定 db_column,因为您只是将其设置为字段的名称

finance = models.ForeignKey(Finance)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM