在DRF中使用ManytoMany字段添加额外的字段

时间:2020-07-30 08:44:01

标签: python-3.x django-rest-framework

我正在尝试创建要在其中添加ManytoMany字段的额外字段的模型类。在某些Google搜索中,我确定了实现through的可能性,但遇到了一些我无法确定问题所在的错误。这是我的模型课:

class CompQuantity(models.Model):
    comp_code = models.ForeignKey(
        'core.SensorDevice',
        on_delete=models.CASCADE,
        null=True
    )
    quantity = models.IntegerField()

class PackageComponent(models.Model):
    pkg_code = models.CharField(max_length=255)
    package = models.ManyToManyField(
        'core.Component',
        through='CompQuantity', 
        through_fields=('comp_code', 'quantity')
    )
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)

我想在PackageComponent中实现什么,我想将包创建为ManytoMany字段,将其与Component表的另一个字段Quantity建立在一起。但是我收到以下错误:

ERRORS:
oss.CompQuantity: (fields.E336) The model is used as an intermediate model by 'oss.PackageComponent.package', but it does not have a foreign key to 'PackageComponent' or 'Component'.
oss.PackageComponent.package: (fields.E339) 'CompQuantity.comp_code' is not a foreign key to 'PackageComponent'.
oss.PackageComponent.package: (fields.E339) 'CompQuantity.quantity' is not a foreign key to 'SensorDevice'.
        HINT: Did you mean one of the following foreign keys to 'Component': comp_code?

我无法理解为什么出现此错误。任何帮助将不胜感激。谢谢

0 个答案:

没有答案