如何在Django中的多个表中设置独特的约束?
我们有两个模型,它们是一对一关系:
class A(models.Model):
first_field_A = ...
second_field_A = ...
class B(models.Model):
first_field_B = ...
a = models.OneToOneField(A, on_delete=models.CASCADE)
我需要定义first_field_a
和second_field_a
的唯一约束和
first_field_b
的模型b
。
那甚至可能吗?
我已经尝试过:
class A(models.Model):
...
class Meta:
constraints = [UniqueConstraint(name='unique_constraint',
fields=['first_field_A', 'second_field_A', 'b__first_field_B']
)
]
而且我有一个错误:
django.core.exceptions.FieldDoesNotExist: A has no field named 'b__first_field_B'
为什么我们无法访问相关表的字段?
什么是选择?
We have two models, they are in One to One relationship:
class A(models.Model):
first_field_A = ...
second_field_A = ...
class B(models.Model):
first_field_B = ...
a = models.OneToOneField(A, on_delete=models.CASCADE)
I need to define a Unique Constraint for first_field_A
and second_field_A
of model A
and first_field_B
of model B
.
Is that even possible?
I have tried this:
class A(models.Model):
...
class Meta:
constraints = [UniqueConstraint(name='unique_constraint',
fields=['first_field_A', 'second_field_A', 'b__first_field_B']
)
]
and I've got this error:
django.core.exceptions.FieldDoesNotExist: A has no field named 'b__first_field_B'
Why we don't have access to fields of related tables?
What is the alternative?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的类定义不正确,您应该在类中移动关系字段,您必须在其中设置唯一的约束
Your class Definition is not correct , you should move relationship field in class where you have to set unique constraints like that