在DJANGO模型中添加条件外键字段

时间:2017-02-18 12:03:09

标签: python django

Models.py 如下所示。 Release表有一个外键 system_requirements_id ,它指向 SystemRequirement 表,但我希望用户只应填写 system_requirements_id Release表中的system_requirements字段中没有文本。否则, system_requirements_id 可以留空。我该如何实现?

class SystemRequirement(TimeStampedModel):
    code_name = models.TextField(blank=True)
    content = models.TextField()
    creation_date = models.DateField(auto_now=False, auto_now_add=True)

    def __unicode__(self):
        return self.code_name

class Release(TimeStampedModel):
    system_requirements = models.TextField(blank=True)
    system_requirements_id = models.ForeignKey(SystemRequirement,
    blank=True, null=True)

1 个答案:

答案 0 :(得分:0)

我的建议是: -

Models.py -

class Release(TimeStampedModel):
    system_requirements_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    system_requirements = models.TextField(blank=True)



class SystemRequirement(TimeStampedModel):
    system_requirements_id = models.ForeignKey(Release)
    code_name = models.TextField(blank=True)
    content = models.TextField()
    creation_date = models.DateField(auto_now=False, auto_now_add=True)

    def __unicode__(self):
        return self.code_name

views.py-(查询)

#check system_requirements text in Release table
try:
    SystemRequirement =     Release.objects.get(system_requirements='MatchingText')

    #If got matching result means text exist so don't do anything

except ObjectDoesNotExist: #No matching query
    Release.objects.filter(system_requirements='MatchingText').update(system_requirements_id='SomeId')