Django表关系有两个字段引用的多个表

2024-10-03 11:17:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于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

提前谢谢你的帮助。你知道吗

表格位置

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

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

表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

Tags: postrueismodelsthishglengthmax
1条回答
网友
1楼 · 发布于 2024-10-03 11:17:38

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

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

相关问题 更多 >