我正在使用 Django 1.9。我有一个简单的模型:
#Goods
class Goods(models.Model):
code = models.CharField(max_length=50)
decription = models.CharField(max_length=100)
...etc
#Vendors
class Vendors(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=100)
...etc
和一个类来定义多个供应商以获得一个好的。
#Purchase_options
class PurchaseOptions(models.Model):
preferred_vendor = models.BooleanField()
vendor = models.ForeignKey(Vendors)
good = models.ForeignKey(Goods)
这是问题: 我怎样才能确保只有一个特定商品的供应商可以设置为首选供应商?。
表中接受的值:
**Vendor | Product | Preferred**
V_01 | Good_01 | True
V_02 | Good_01 | False
V_03 | Good_01 | False
V_02 | Good_02 | True
V_04 | Good_02 | False
表格中的错误值:
**Vendor | Product | Preferred**
V_01 | Good_01 | True
V_02 | Good_01 | **True** <-There's already a preferred vendor.
V_03 | Good_01 | False
V_02 | Good_02 | True
V_04 | Good_02 | False
我正在使用 Django 的管理界面来填充 Puchase_Options 上的数据。 我试过这个:
1) 定义一个验证器,给定首选值和产品 ID,检查该组合是否存在于表中:
def validator(preferred, id):
if Purchase_Option.objects.filter(good.id=id,preferred_vendor=preferred).exists():
Raise ValidationError("There's already a preferred vendor defined for this product")
但它告诉我对象 Purchase_Options 不存在。我相信我实际上无法在验证器函数中查询数据库或处理查询集。
2) 我尝试使用元属性 unique-together("preferred_vendor","good_id")。那会起作用,除了我必须允许 False + Good_Id 的多种组合(因为我有很多非首选供应商)......但只有 True+Good_id 的 1 种组合.
我真的不知道还能尝试什么,我真的很期待听到您的想法。你之前多次救过我:D
最佳答案
你可以使用 NullBooleanField
对于 preferred_vendor
,和 unique_together
对于 preferred_vendor
和 good
。对一个首选供应商使用 True
,对所有其他供应商使用 NULL
而不是 False
。
这将允许您有多对 (good
, NULL
) 和只有一对 (good
,True
)。缺点是您也只能有一对(good
,False
),但这应该不是问题。
例如:
class PurchaseOptions(models.Model):
preferred_vendor = models.NullBooleanField()
vendor = models.ForeignKey(Vendors)
good = models.ForeignKey(Goods)
class Meta:
unique_together = ("preferred_vendor", "good")
然后:
Vendor | Product | Preferred
V_01 | Good_01 | True
V_02 | Good_01 | NULL
V_03 | Good_01 | NULL
V_02 | Good_02 | True
V_04 | Good_02 | NULL
关于python - Django 验证列组合是否存在( bool 字段唯一),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36013167/