如何在另一个表(Django)中正确执行字段组合?

如何在另一个表(Django)中正确执行字段组合?,django,django-models,Django,Django Models,我有Outcode模型,它与SubOutcode模型有一对多的关系: class Outcode(models.Model): outcode = models.CharField(max_length=4, primary_key=True) class Meta: managed = True db_table = 'outcode' class SubOutcode(models.Model): outcode = models.

我有
Outcode
模型,它与
SubOutcode
模型有一对多的关系:

class Outcode(models.Model):
    outcode = models.CharField(max_length=4, primary_key=True)

    class Meta:
        managed = True
        db_table = 'outcode'
class SubOutcode(models.Model):
    outcode = models.ForeignKey('Outcode', models.DO_NOTHING)
    sub_outcode = models.CharField(max_length=4, default="")

    class Meta:
        managed = True
        constraints = [
            models.UniqueConstraint(fields=['outcode', 'sub_outcode'], name='unq_sub_outcode')
        ]
        db_table = 'sub_outcode'
SubOutcode
型号:

class Outcode(models.Model):
    outcode = models.CharField(max_length=4, primary_key=True)

    class Meta:
        managed = True
        db_table = 'outcode'
class SubOutcode(models.Model):
    outcode = models.ForeignKey('Outcode', models.DO_NOTHING)
    sub_outcode = models.CharField(max_length=4, default="")

    class Meta:
        managed = True
        constraints = [
            models.UniqueConstraint(fields=['outcode', 'sub_outcode'], name='unq_sub_outcode')
        ]
        db_table = 'sub_outcode'
仅当
子输出代码
中存在匹配的字段组合时,我才希望能够创建
属性
记录。如何正确设置
属性
?如果
Outcode
SubOutcode
分别存在,我当前的设置看起来不起作用,如下所示,但我希望
属性
强制执行该组合(如果有意义)?谢谢你的帮助

class Property(models.Model):     

    property_outcode = models.ForeignKey('Outcode', models.DO_NOTHING)
    property_sub_outcode = models.ForeignKey('SubOutcode', models.DO_NOTHING, to_field='sub_outcode')

在上面的代码中,子输出代码实例只有在引用了输出代码实例时才能存在。这是因为您没有在子输出代码的外键上设置
null=True

因此,您可以只删除属性模型上的属性\u outcode,因为其子outcode必须具有指向outcode实例的外键:

类属性(models.Model):
property\u sub\u outcode=models.ForeignKey('SubOutcode',models.DO\u NOTHING,to\u field='sub\u outcode'))
现在,仅当对子输出代码的引用也具有输出代码实例时,属性实例才会始终存在

如果您有一个property_实例,并且希望知道其子输出代码引用的输出代码实例,请使用:
property\u instance.property\u sub\u outcode.outcode