我应该如何在 django admin 中表示位标志 int 字段?

发布于 2024-09-14 04:04:39 字数 975 浏览 9 评论 0原文

我有一个数据模型,其位字段定义如下:

alter table MemberFlags add column title varchar(50) not null default '';
alter table MemberFlags add column value integer( 3) not null default 0;

insert into MemberFlags (title, value) values
    ("Blacklisted",             1),
    ("Special Guest",           2),
    ("Attend Ad-hoc Sessions",  4),
    ("Attend VIP Sessions",     8),
    ("Access Facility A",      16),
    ("Access Facility B",      32)

并像这样使用:

alter table Membership add column title varchar(50) not null default '';
alter table Membership add column flags integer( 3) not null default 0;

insert into Membership (title, flags) values
    ("Guest Pass",          4+2 ),
    ("Silver Plan",    16+  4   ),
    ("Gold Plan",   32+16+  4+2 ),
    ("VIP Pass",    32+16+8+4+2 )

我的问题是:

A)将不同位标志表示为管理站点中单独项目的最简单方法是什么?我应该覆盖模板,还是对表单做一些事情?

B) 搜索列表怎么样?我可以在模型中创建函数来表示每一位,但是如何进行搜索和排序呢?

我是姜戈的新手。

I have a data model with a bitfield defined something like this:

alter table MemberFlags add column title varchar(50) not null default '';
alter table MemberFlags add column value integer( 3) not null default 0;

insert into MemberFlags (title, value) values
    ("Blacklisted",             1),
    ("Special Guest",           2),
    ("Attend Ad-hoc Sessions",  4),
    ("Attend VIP Sessions",     8),
    ("Access Facility A",      16),
    ("Access Facility B",      32)

And used like this:

alter table Membership add column title varchar(50) not null default '';
alter table Membership add column flags integer( 3) not null default 0;

insert into Membership (title, flags) values
    ("Guest Pass",          4+2 ),
    ("Silver Plan",    16+  4   ),
    ("Gold Plan",   32+16+  4+2 ),
    ("VIP Pass",    32+16+8+4+2 )

My questions are:

A) What's the easiest way to represent the different bitflags as separate items in the admin site? Should I override the template, or do something with forms?

B) How about the search list? I could create functions in the model to represent each bit, but how would searching and sorting be done?

I'm new to Django.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

安静被遗忘 2024-09-21 04:04:39

一个经过测试的优秀解决方案,即使它不能立即适合您的模型,也可以使用 django-bitfield

A great tested solution, even if it doesn't fit your model right away, would be using django-bitfield

还给你自由 2024-09-21 04:04:39

我认为最好的解决方案是通过子类化 models.Field 来创建新的字段类型。您可以使用 choices 参数来分配有效位标志及其含义。这将有助于保持模型声明的整洁和可读性,最终结果如下:

class BitFlagField(models.Field):

    ...

class MyModel(models.Model):

    ...

    FLAG_CHOICES = (
        (1, 'Blacklisted'),
        (2, 'Special Guest'),
        (4, 'Attend Ad-hoc Sessions'),
        (8, 'Attend VIP Sessions'),
        (16, 'Access Facility A'),
        (32, 'Access Facility B'),
    )
    flags = BitFlagField(choices=FLAG_CHOICES)

   ...

Django 文档有一篇关于如何子类化模型的深入文章。字段:

编写自定义模型字段
它似乎涵盖了您需要做的所有事情,包括:

  • a-model-field" rel="nofollow noreferrer">指定表单字段 ( djangoproject.com/en/1.8/howto/custom-model-fields/#preparing-values-for-use-in-database-lookups" rel="nofollow noreferrer">准备查找值(这将允许您可以使用该字段进行搜索和过滤。)

如果您正在寻找子类字段的示例,此片段可能有用。它的目标是相似的(多个选择作为模型字段),但将它们存储在数据库中的方式不同(它使用 CSV 文本字段而不是位标志)。

I think the best solution here would be for you to create a new field type by subclassing models.Field. You could make use of the choices parameter to assign the valid bit flags and their meanings. This would help keep your model declaration clean and readable, with a final result along the lines of:

class BitFlagField(models.Field):

    ...

class MyModel(models.Model):

    ...

    FLAG_CHOICES = (
        (1, 'Blacklisted'),
        (2, 'Special Guest'),
        (4, 'Attend Ad-hoc Sessions'),
        (8, 'Attend VIP Sessions'),
        (16, 'Access Facility A'),
        (32, 'Access Facility B'),
    )
    flags = BitFlagField(choices=FLAG_CHOICES)

   ...

The Django documentation has a great in-depth article on how to go about subclassing models.Field:

Writing Custom Model Fields
It seems to cover everything you need to do, including:

If you're looking for an example of a subclassed field, this snippet might be of use. Its goal is similar (multiple choices as a model field), but its manner of storing them in the database differs (it's using a CSV text field instead of bit flags).

鹿! 2024-09-21 04:04:39

根据安德鲁的回答中的片段,您需要进行以下更改:

from django.db import models
from django import forms

class BitFlagFormField(forms.MultipleChoiceField):
    widget = forms.CheckboxSelectMultiple

    def __init__(self, *args, **kwargs):
        super(BitFlagFormField, self).__init__(*args, **kwargs)

class BitFlagField(models.Field):
    __metaclass__ = models.SubfieldBase

    def get_internal_type(self):
        return "Integer"

    def get_choices_default(self):
        return self.get_choices(include_blank=False)

    def _get_FIELD_display(self, field):
        value = getattr(self, field.attname)
        choicedict = dict(field.choices)

    def formfield(self, **kwargs):
        # do not call super, as that overrides default widget if it has choices
        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 
                    'help_text': self.help_text, 'choices':self.choices}
        if self.has_default():
            defaults['initial'] = self.get_default()
        defaults.update(kwargs)
        return BitFlagFormField(**defaults)

    def get_db_prep_value(self, value):
        if isinstance(value, int):
            return value
        elif isinstance(value, list):
            return sum(value)

    def to_python(self, value):
        result = []
        n = 1
        while value > 0:
            if (value % 2) > 0:
                result.append(n)
            n *= 2
            value /= 2
        return sorted(result)


    def contribute_to_class(self, cls, name):
        super(BitFlagField, self).contribute_to_class(cls, name)
        if self.choices:
            func = lambda self, fieldname = name, choicedict = dict(self.choices):" and ".join([choicedict.get(value,value) for value in getattr(self,fieldname)])
            setattr(cls, 'get_%s_display' % self.name, func)

Working off the snippet in Andrew's answer, here are the changes you'd need to make:

from django.db import models
from django import forms

class BitFlagFormField(forms.MultipleChoiceField):
    widget = forms.CheckboxSelectMultiple

    def __init__(self, *args, **kwargs):
        super(BitFlagFormField, self).__init__(*args, **kwargs)

class BitFlagField(models.Field):
    __metaclass__ = models.SubfieldBase

    def get_internal_type(self):
        return "Integer"

    def get_choices_default(self):
        return self.get_choices(include_blank=False)

    def _get_FIELD_display(self, field):
        value = getattr(self, field.attname)
        choicedict = dict(field.choices)

    def formfield(self, **kwargs):
        # do not call super, as that overrides default widget if it has choices
        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 
                    'help_text': self.help_text, 'choices':self.choices}
        if self.has_default():
            defaults['initial'] = self.get_default()
        defaults.update(kwargs)
        return BitFlagFormField(**defaults)

    def get_db_prep_value(self, value):
        if isinstance(value, int):
            return value
        elif isinstance(value, list):
            return sum(value)

    def to_python(self, value):
        result = []
        n = 1
        while value > 0:
            if (value % 2) > 0:
                result.append(n)
            n *= 2
            value /= 2
        return sorted(result)


    def contribute_to_class(self, cls, name):
        super(BitFlagField, self).contribute_to_class(cls, name)
        if self.choices:
            func = lambda self, fieldname = name, choicedict = dict(self.choices):" and ".join([choicedict.get(value,value) for value in getattr(self,fieldname)])
            setattr(cls, 'get_%s_display' % self.name, func)
踏月而来 2024-09-21 04:04:39

这就是我在 User 类中使用标志的方式:

FLAGS = {
    1:"Blacklisted",
    2:"SpecialGuest",
    4:"AttendAd-hocSessions",
    8:"AttendVIPSessions",
    16:"AccessFacilityA",
    32:"AccessFacilityB",
}

class User(object):
    def __init__(self, name="John Doe", groups=0):
        self.name = name
        self.groups = groups
    def memberof(self):
        ''' Display string representation of the groups. '''
        for flag in sorted(FLAGS):
            if (flag & self.groups) == flag:
                print FLAGS[flag]

当然,您可以创建一个以逗号分隔的字符串来显示在管理视图中,或者您想要的任何内容,而不是打印标志。

对于管理员,只需为每个使用 布尔值团体价值观。

This is how I would use the flags with my User class:

FLAGS = {
    1:"Blacklisted",
    2:"SpecialGuest",
    4:"AttendAd-hocSessions",
    8:"AttendVIPSessions",
    16:"AccessFacilityA",
    32:"AccessFacilityB",
}

class User(object):
    def __init__(self, name="John Doe", groups=0):
        self.name = name
        self.groups = groups
    def memberof(self):
        ''' Display string representation of the groups. '''
        for flag in sorted(FLAGS):
            if (flag & self.groups) == flag:
                print FLAGS[flag]

Of course instead of printing the flags, you can create a comma-separated string to display in the admin view, or whatever you desire.

For the admin, just use a boolean for each of the group values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文