django - 限制django中ManyToManyField中关系的数量

标签 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

一切正常,除了我无法对每个陈列室的类别数量进行验证。我不是在 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/

相关文章:

python - mod_wsgi 解析 WSGI 脚本文件失败 |处理 WSGI 脚本时发生异常 |无法导入 'site' 模块

python - 预取 Django 模型属性

python - Django - 将图像添加到 Django 管理中的列表显示

django - ModelSerializer 在 Django REST 框架中非常慢

python - 评估一个数据库命中中的整个 django 查询集

Python Django 2.0 十进制字段 "Ensure that there are no more than 3 digits before the decimal point"

Django:ORM 是否支持 SQL "IN"运算符?

python - 将具有多个循环和逻辑的代码简化为查询集聚合

python - Django 事务管理 block 以未决的 COMMIT/ROLLBACK 结束

mysql - 什么是 SELECT col1 FROM table WHERE col2=somestring 的 Django ORM 等价物?