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

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

问题描述

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



这是可能吗?我有一种感觉,我已经看到这样做,但不幸的是我无法找到它。



编辑:
我需要这个一个愚蠢的简单的CMS。我有一个抽象类,FrontPage和Page类继承。我只想能够创建一个frontpage对象。



FrontPage对象和Page对象之间的区别是它们应该有稍微不同的字段和模板,并且只提到一个FrontPage将被创建。

解决方案

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

 从django.db导入模型
从django.core.exceptions导入ValidationError

def validate_only_one_instance(obj):
model = obj .__ class__
if(model.objects.count()> 0和
obj.id!= model .objects.get()。id):
raise ValidationError(只能创建1%的实例%模型.__ name__)

类示例(models.Model):

def clean(self):
validate_only_one_instance(self)

只能防止th创建新的实例,但是Django管理UI实际上会报告创建失败,原因是只能创建1个示例实例(而文档中的早期返回方法则没有指示为为什么保存不起作用)。


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.

EDIT: 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.

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.

解决方案

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)

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天全站免登陆