Django - 具有单个True的布尔字段 [英] Django - Boolean field with Single True

查看:147
本文介绍了Django - 具有单个True的布尔字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个布尔字段,只允许其中的一个是基于外键( )的 True 。我现在确定如何说这个或真正搜索它,但我能够得到一个简单的实现工作,但我不喜欢它。它感觉笨重和错误。无论如何,最好的方式来获得我的意思是你看到它,在这里你去:

I want a boolean field that only allows for ONE of them to be True based on a foreign key (User). I am now sure how to word this or really search for it, but I was able to get a simple implementation working, but I do not like it. It feels clunky and wrong. Anyways, the best way to get what I mean is you see it, here you go:

class MyModel(models.Model):
    owner = models.ForeignKey(User)
    _is_main = models.BooleanField(default=False)

    def __get_is_main(self):
        return self._is_main

    def __set_is_main(self, is_main):
        if (is_main):
            active_keys = API_Key.objects.filter(_is_main=True, owner=self.owner)
            if (len(active_keys) == 1 and self in active_keys):
                return
            else:
                for key in active_keys:
                    if (key.is_main):
                        key.is_main = False
                        key.save()
        self._is_main = is_main
        self.save()

    is_main = property(__get_is_main, __set_is_main)

我只想让每个所有者的is_main成为 > ONCE,不再一次。这些是用于API密钥。因此,所有者可以有多个API密钥,但只有一个设置为主密钥。这是我可以找出如何实现这一点的唯一方法。任何人都有更好的方法来做到这一点?

I only want is_main to be True for each owner ONCE, no more then once. These are for API keys. So the owner can have many API Keys but only one is set to the main one. This is the only way I could figure out how to implement this. Anyone have a better way to do this? I am using MySQL if it matters.

推荐答案

也许你不需要这个字段,但是有一个singleton指向一个主键。沿着这些线:

Maybe you don't need that field but have a singleton pointing to a main key. Something along these lines:

class Key(models.Model):
    owner = models.ForeignKey(User)

    @property
    def is_main(self):
        return hasattr(self, 'is_main')

    def set_main(self):
        # update MainKey instance here


class MainKey(models.Model):
    key = models.ForeignKey(Key, related_name='is_main')

    def save(self, *args, **kwargs):
        self.id = 1
        super(MainKey, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        pass

这篇关于Django - 具有单个True的布尔字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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