在我有陈列室及其类别的场景中,我在我的代码中使用 ManyToMany 关系。现在陈列室最多可以分为三个类别,我必须在保存时对其进行验证。下面是我的代码:
##models.py
class Showrooms(models.Model):
name = models.CharField(max_length = 100)
contact_person = models.CharField(max_length = 100)
offer = models.TextField()
categories = models.ManyToManyField(Categories, null=True, blank=True, related_name='categories')
class Meta:
db_table = 'showrooms'
verbose_name_plural = "showrooms"
class Categories(models.Model):
category = models.CharField(max_length = 100)
image = models.ImageField(upload_to = showroom_upload_path, null=True, blank=True)
slug = models.SlugField(blank=True)
class Meta:
db_table = 'showroom_categories'
verbose_name_plural = "categories"
def __str__(self):
return self.category
一切正常,除了我无法对每个陈列室的类别数量进行验证。我不是在 View 中使用它,而是想在管理中使用它。
请帮忙
谢谢
编辑
好的..我已经解决了我的问题。我在 forms.py 中创建了一个表单
class ShowroomsForm(forms.ModelForm):
class Meta:
model = Showrooms
def clean(self):
categories = self.cleaned_data.get('categories')
if categories and categories.count() > 3:
raise ValidationError('Maximum three categories are allowed.')
return self.cleaned_data
并将其添加到 admin.py 如下:
class ShowroomsAdmin(admin.ModelAdmin):
form = ShowroomsForm
admin.site.register(Showrooms, ShowroomsAdmin)
最佳答案
你可以在你的模型上定义一个 clean() 方法,只要一个陈列室被分配到 3 个以上的类别,就会引发验证错误。
https://docs.djangoproject.com/en/1.5/ref/models/instances/#django.db.models.Model.clean
关于django - 限制django中ManyToManyField中关系的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21547728/