Django表关系manytomany有两个字段参考

时间:2018-07-22 14:49:11

标签: python django database manytomanyfield

我有一个与Django中的数据库关系有关的问题。 共有三个表,请参见下文。通过Foreignkey方法成功建立了KbMeta和Tdb之间的关系。但是我不知道如何管理Posd和Tdb之间的关系。位置“ hg”和“ pos”在Posd表中是唯一的,但在Tdb表中不是唯一的。但是,当我比较HG和POS字段时,我应该获得正确的参考。以下方法不适用于Tdb表:

posd = models.ManyToManyField(Posd, through='Posd', through_fields=('hg','pos')) # This is wrong, doesn't work

在此先感谢您的帮助。

TABLE Posd

class Posd(models.Model):
#This class is just repsresenting the cost position in KBSUMME
hg = models.IntegerField()
pos = models.IntegerField()
description = models.CharField(max_length=200)
hours = models.CharField(max_length=5)
cost = models.CharField(max_length=5)

class Meta:
    unique_together = (('hg', 'pos'),)

TABLE KbMeta

class KbMeta(models.Model):
#This class is representing the meta data for one project. One row per project only.
pid = models.IntegerField(primary_key=True)
klaversion = models.CharField(max_length=50, blank=True)
calcbase = models.CharField(max_length=10, blank=True)
contractbase = models.CharField(max_length=10, blank=True)
quotno = models.CharField(max_length=50)
filename = models.CharField(max_length=100)
datecalc = models.DateField(default='1999-09-09')
dateupload = models.DateTimeField(default='1999-09-09')
projname = models.CharField(max_length=100, blank=True)
customer = models.CharField(max_length=100, blank=True)
endcustomer = models.CharField(max_length=100, blank=True)
phase = models.CharField(max_length=50, blank=True)

TABLE Tdb

class Tdb(models.Model):
#This is the T detail cost calculation
hg = models.IntegerField()
pos = models.IntegerField()
hours = models.FloatField()
cost = models.FloatField()
kbmeta = models.ForeignKey(KbMeta, on_delete=models.CASCADE)
posd = models.ManyToManyField(Posd, through='Posd', through_fields=('hg','pos')) # This is wrong, doesn't work

1 个答案:

答案 0 :(得分:0)

要建立该关系,您需要指定一个中介表,如文档link所示。但是为此,您还需要hgpos作为主键,这是一个多列主键,django不支持see here。我可以看到的可能解决方案是:

  1. 修改您的Posd和Tbd模型,以便它们可以通过唯一的列关联
  2. 使用原始sql将hgpos用作主键