Using Django Check Constraints to Ensure Only One Field Is Set

栏目: IT技术 · 发布时间: 4年前

内容简介:I previously covered usingA project I was working on recently stores “scores” which may have a single typed value: an integer, or a decimal, or a duration. Because they have different types, they are stored in separate columns in the database. Therefore, f
Using Django Check Constraints to Ensure Only One Field Is Set

I previously covered using Django’s CheckConstraint class to validate fields with choices and percentage fields that total 100% . Here’s another use case.

A project I was working on recently stores “scores” which may have a single typed value: an integer, or a decimal, or a duration. Because they have different types, they are stored in separate columns in the database. Therefore, for a single score, only one of these columns may be filled in (not null).

You could solve this by using model inheritance . The downside of this is that using either concrete or abstract inheritance, you’d need multiple tables. This is also a lot of work for a single differing field.

Instead of this, we settled on a single model appraoch with multiple value columns, only one of which should be set. The model looks something like this:

from django.db import models

class ScoreType(models.IntegerChoices):
    POINTS = 1, 'Points'
    DURATION = 2, 'Duration'


class Score(models.Model):
    type = models.IntegerField(choices=ScoreType.choices)
    value_points = models.IntegerField()
    value_duration = models.DurationField()

( IntegerChoices is one of Django 3.0’s newenumeration types.)

If type is ScoreType.POINTS , the value_points column should be set. And likewise, if the type is ScoreType.DURATION , the value_duration column should be set.

However confident you are in our Python code satisfying this constraint, unless you make the database enforce it, a single bug could break the assumption. For example you could accidentally write a query like:

Score.objects.update(value_points=1, value_duration=dt.timedelta(1))

(Importing datetime as dt .)

Such bad data could have all kinds of unintended consequences. If you discover such bad data has been ongoign for some time, it might take a long time to unravel. Best to prevent it early on if you can!

To do this, you can add a CheckConstraint to enforce that the filled-in value column matches the type . It would look this:

from django.db import models


class ScoreType(models.IntegerChoices):
    POINTS = 1, "Points"
    DURATION = 2, "Duration"


class Score(models.Model):
    type = models.IntegerField(choices=ScoreType.choices)
    value_points = models.IntegerField(null=True)
    value_duration = models.DurationField(null=True)

    class Meta:
        constraints = [
            models.CheckConstraint(
                name="score_value_matches_type",
                check=(
                    models.Q(
                        type=ScoreType.POINTS,
                        value_points__isnull=False,
                        value_duration__isnull=True,
                    )
                    | models.Q(
                        type=ScoreType.DURATION,
                        value_points__isnull=True,
                        value_duration__isnull=False,
                    )
                ),
            )
        ]

THe constraint is defined with Q objects, which take the same arguments as filter() , to restrict the cases. Here we essentially list the two valid cases, and OR them together with Python’s bitwise OR operator | . Q can’t use the normal or operator for this because of limitations in Python.

After makemigrations and applying this migration, you can test the constraint out. You can create legitimate Score instances just fine:

In [3]: Score.objects.create(type=ScoreType.POINTS, value_points=1337)
Out[3]: <Score: Score object (1)>

In [4]: Score.objects.create(type=ScoreType.DURATION, value_duration=dt.timedelta(seconds=1234))
Out[4]: <Score: Score object (2)>

But if you try save bad data, you will get an IntegrityError :

In [5]: Score.objects.create(type=ScoreType.POINTS, value_points=1337, value_duration=dt.timedelta(seconds=1234))
...
IntegrityError: CHECK constraint failed: score_value_matches_type

This works great.

You can also combine this with proxy models to split Score s based on type. I haven’t played around with this fully but it looks like a viable alternative to multi-table inheritance. You could even add a helper to generate classes automatically.

You can make a simple “Points” implementation without any automatic generation like this:

class PointsScoreManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(type=ScoreType.POINTS)


class PointsScore(Score):
    objects = PointsScoreManager()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.type = ScoreType.POINTS

    class Meta:
        proxy = True

The DURATION implementation just needs a little copy-paste-replace.

This uses a custom manager to only returns instances of the right type. And it also overrides __init__ to force the type . I’m sure there are some other overrides to add to make this a smooth experience, but you get the idea.

Fin

For the source code of the example project used in this post, including a bonus auto-generation of the check constraint, see it here on GitHub .

I hope this post helps you further your CheckConstraint applications,

—Adam

Interested in Django or Python training?I'm taking bookingsfor workshops.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

网络营销实战密码

网络营销实战密码

昝辉Zac / 电子工业出版社 / 2009.1 / 56.00元

本书是作者几年来网络营销实战的总结,与其他网络营销书籍最大不同之处是:只专注于实战,不谈理论。本书分三部分详细介绍了网络营销实用策略和技巧,并分析了大量实战案例。第一部分介绍市场与产品研究,包括用户、市场和竞争对手的调查;产品、目标市场的确定;价格策略;赢利模式等。第二部分讨论以网络营销为导向的网站设计,包括怎样在网站上卖东西、提高转化率,以及网站目标设定等。第三部分研究怎样给网站带来流量,详细讨......一起来看看 《网络营销实战密码》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试