用字段名称_id来保存FK模型字段允许存在不存在的FK关系。

2024-06-08 19:11:42 发布

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

我有一个由两个ForeignKey字段组成的模型,如下所示(这是一个多个through字段)

class EntityConceptLink(models.Model):
    entity = models.ForeignKey(Entity)
    standard_concept = models.ForeignKey(StandardConcept)
    other fields...

我正在尝试创建这样的对象:

EntityConceptLink.objects.get_or_create(
    entity_id=entity_id,  # passing in an integer, should be PK of Entity
    standard_concept=concept)  # passing in a model instance

问题是,当我传入一个与一个不存在的实体相对应的实体id时,上面的代码还是以某种方式保存了模型实例。直到后来当我尝试执行entityconceptlinkinstance.entity时,才引发了一个DoesNotExist: Entity matching query does not exist

在尝试保存过程中,模型不应该验证失败吗?我做错什么了吗


Tags: in模型实体idmodelmodelsconceptstandard
1条回答
网友
1楼 · 发布于 2024-06-08 19:11:42

是的,我认为下面的代码应该可以正常工作

EntityConceptLink.objects.get_or_create(
    entity__id=entity_id,  # Believe `id` would be the primary key
    standard_concept=concept)

在上述情况下,如果实体模型找不到所需的id,则会引发错误。请参阅在实体id中使用双__而不是单_

相关问题 更多 >