我想在django中创建一个不重复选择的问题对象。类似:
1) 2
2) 5
3) 5
4) 7
2和3具有相同的值,应该抛出错误或响应(我使用的是rest框架(
# models.py
class Question(models.Model):
field = models.ForeignKey('Field', on_delete=models.CASCADE)
writer = models.ForeignKey(User, on_delete=models.CASCADE)
question = models.TextField(unique=True)
choice1 = models.CharField(max_length=200)
choice2 = models.CharField(max_length=200)
choice3 = models.CharField(max_length=200)
choice4 = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
approved = models.BooleanField(default=False)
ignored = models.BooleanField(default=False)
这个问题有什么解决办法吗?
有一个简单的解决方案,名为unique_together,可以满足您的需求。
例如:
class MyModel(models.Model):
field1 = models.CharField(max_length=50)
field2 = models.CharField(max_length=50)
field3 = models.CharField(max_length=50)
field4 = models.CharField(max_length=50)
class Meta:
unique_together = ('field1', 'field2', 'field3', 'field4',)
在您的情况下:
class Question(models.Model):
field = models.ForeignKey('Field', on_delete=models.CASCADE)
writer = models.ForeignKey(User, on_delete=models.CASCADE)
question = models.TextField(unique=True)
choice1 = models.CharField(max_length=200)
choice2 = models.CharField(max_length=200)
choice3 = models.CharField(max_length=200)
choice4 = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
approved = models.BooleanField(default=False)
ignored = models.BooleanField(default=False)
class Meta:
unique_together = ('choice1', 'choice2', 'choice3', 'choice4',)