限制模型中每个用户可以具有值的记录数 [英] Limit the number of records in a Model that can have a value per user

查看:42
本文介绍了限制模型中每个用户可以具有值的记录数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,其布尔字段名为 is_active .我想将 user 可以具有的模型数量限制为布尔值的值为 True 到1.

I have a Model with a boolean field named is_active. I want to limit the number of models a user can have where the value of that boolean field is True to 1.

class MyModel(models.Model):
    user = models.ForeignKey(User)
    is_active = models.BooleanField(default=False)
    #...more fields ...

最初,我只是要在 Meta 中添加一个 unique_togeather =("user","is_active")条目-但当然,这也会限制该数量 User 可以具有的 False 个条目-我需要不受限制.

Initially I was just going to add a unique_togeather = ("user", "is_active") entry to Meta -- but of course that will also limit the number of False entries a User can have -- which I need to be unlimited.

理想情况下,我想在数据库级别解决此问题,以防止出现竞争情况.

Ideally, I'd like to solve this at the database level to prevent race conditions.

通过Celery任务使用 MyModel.objects.get_or_create()导入数据来创建模型-因此,由于Celery工人的并发程度,极有可能发生竞争情况

The models are being created by Celery tasks importing data using MyModel.objects.get_or_create() -- so it is very possible that a race condition could occur due to the level of concurrency from Celery workers.

推荐答案

您应该在模型上创建自定义清理方法.

You should create custom clean method on your model.

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

class MyModel(models.Model):
    user = models.ForeignKey(User)
    is_active = models.BooleanField(default=False)
    #...more fields ...

    def clean(self):
        if not self.pk and MyModel.objects.filter(user=self.user, is_active=True).exists():
            raise ValidationError('How about no?')

这篇关于限制模型中每个用户可以具有值的记录数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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