限制django中ManyToManyField中的关系数

时间:2014-02-04 08:50:14

标签: django django-models django-orm

我在我的代码中使用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

一切正常,但我无法对每个展厅的类别数量进行验证。我不是在视图中使用它,而只是想在管理中执行它。

请帮忙

由于

编辑

好的..我已经解决了我的问题。我在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)

1 个答案:

答案 0 :(得分:2)

您可以在模型上定义一个clean()方法,每当展厅被分配到3个以上的类别时,就会引发验证错误。

https://docs.djangoproject.com/en/1.5/ref/models/instances/#django.db.models.Model.clean