Django:是否可以将外键字段添加到"unique_together"? [英] Django: Is there a way to add a foreign key field to "unique_together"?

查看:69
本文介绍了Django:是否可以将外键字段添加到"unique_together"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使模型的唯一性来自外键模型.不确定在Django中是否可行.

I want to be able to make a model unique on a value that comes from a foreign key model. Not sure if that's possible in django.

示例:我的模型A为:

class modelA(models.Model):
    fieldA1 = models.AutoField(primary_key=True)
    fieldA2 = models.CharField(max_length=20)

还有模型B为:

class modelB(models.Model):
    fieldB1 = models.CharField(max_length=20)
    fieldB2 = models.ForeignKey(modelA)

    class Meta:
        unique_together = ('fieldB1', 'fieldB2',<<'fieldA2'>>)

我想将fieldA2添加为模型B的unique_together子句中的属性之一.在Django中可能吗?我不能这样做-

I want to add fieldA2 as one of the attributes in the unique_together clause of model B. Is that possible in Django? I COULD NOT do it as-

unique_together = ('fieldB1', 'fieldB2','modelA__fieldA2')

推荐答案

您不能.数据库约束不能包含此类数据.您将必须在创建实例或编写一些验证器之前以编程方式对其进行检查

you cannot. database constraints cannot contain those kind of data. you will have to check it programmatically before creating instances or write some validator

这篇关于Django:是否可以将外键字段添加到"unique_together"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆