限制要创建的模型实例的数量 - django [英] Limit number of model instances to be created - django

查看:30
本文介绍了限制要创建的模型实例的数量 - django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,我只想从中创建一个实例,不应允许更多实例.

I have model from which I only want to create one instance, and no more instances should be allowed.

这可能吗?我有一种感觉,我在某处看到过这样做,但不幸的是我找不到它.

Is this possible? I've got a feeling that I've seen this done somewhere, but unfortunately I'm unable to locate it.

我需要这个用于愚蠢的简单 CMS.我有一个 FrontPage 和 Page 类继承的抽象类.我只想创建一个首页对象.

I need this for a stupidly simple CMS. I have an abstract class for which FrontPage and Page classes inherits. I only want to be able to create one frontpage object.

FrontPage 对象和 Page 对象之间的区别在于它们应该具有略有不同的字段和模板,并且如上所述只需要创建一个 FrontPage.

The difference between the FrontPage object and the Page objects are that they're supposed to have slightly different fields and templates, and as mentioned only one FrontPage is to be created.

推荐答案

我自己也想做类似的事情,发现 Django 的模型验证提供了一个方便的执行钩子:

I wanted to do something similar myself, and found that Django's model validation provided a convenient hook for enforcement:

from django.db import models
from django.core.exceptions import ValidationError

def validate_only_one_instance(obj):
    model = obj.__class__
    if (model.objects.count() > 0 and
            obj.id != model.objects.get().id):
        raise ValidationError("Can only create 1 %s instance" % model.__name__)

class Example(models.Model):

    def clean(self):
        validate_only_one_instance(self)

这不仅会阻止创建新实例,而且 Django 管理 UI 实际上会报告创建失败,原因是只能创建 1 个示例实例"(而早期返回方法在文档中没有说明为什么保存不起作用).

That not only prevents the creation of new instances, but the Django admin UI will actually report that the creation failed and the reason was "Can only create 1 Example instance"(whereas the early return approach in the docs gives no indication as to why the save didn't work).

这篇关于限制要创建的模型实例的数量 - django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆