2017-03-17 27 views
0

如何保證兩個屬性的獨特組合,不應在以下模型確保兩個屬性的Django模型應該總是不同的 - 唯一的答案是unique_together?

class modelBodyPart(models.Model): 
    area = models.CharField(max_length=128) 
    crush_name = models.CharField(max_length=128) 

重複

例如在modelBodyPart areacrush_name的每個實例應該永遠是不同的

例如一些允許和不允許的結果是:

area = Area_A crush_name=Jenny //OK 
    area = Area_A crush_name=Jordan //OK 
    area = Area_B crush_name=Jenny //OK 
    area = Area_A crush_name=Jenny //Not allowed 

我將如何在模型中實現這一點?我會使用unique_together 我無法完全理解上述鏈接中的情況要求,這就是我在這裏問的原因。

回答

1

是的,你是對你的代碼應該是這樣的 -

models.py

class modelBodyPart(models.Model): 
    area = models.CharField(max_length=128) 
    crush_name = models.CharField(max_length=128) 

    class Meta: 
     unique_together = ['area','crush_name'] 
相關問題