跳转到主要内容

自定义Django模型字段,用于存储多个值。

项目描述

https://api.travis-ci.org/escer/django-collectionfield.svg?branch=master https://img.shields.io/pypi/v/django-collectionfield.svg https://coveralls.io/repos/github/escer/django-collectionfield/badge.svg?branch=master

一个可重用的Django模型字段,用于存储集合。

特性

  • 高度可配置的 模型字段(更改集合和项目类型、排序、选项、项目唯一性和更多)

  • 自定义查找,简化对集合项的查询

  • 表单字段,用于处理集合

  • 集合 项目验证器

  • 扩展的 get_FIELD_display 方法,适用于具有选项的模型字段

  • 与没有原生多值列支持的数据库后端(如PostgreSQL的ArrayField)协同工作

安装

pip install django-collectionfield

用法

模型字段

定义具有存储字符串列表字段的模型

# models.py
from django.db import models
from collectionfield.models import CollectionField

class MyModel(models.Model):
    tags = CollectionField()

将值传递给模型字段

my_model = MyModel.objects.create(tags=['test', 'values'])
my_model.values
['test', 'values']

进行查询

检索具有集合中特定值存在的模型实例

MyModel.objects.filter(tags__has='test')

检索具有集合中 所有 值存在的模型实例(忽略项目的顺序)

MyModel.objects.filter(tags__hasall=['test', 'values'])

检索具有集合中 任何 值存在的模型实例

MyModel.objects.filter(tags__hasany=['test', 'values'])

定制集合

自定义集合和项目类型

class IntegerSet(models.Model):
    # This field will provide sets of integers
    # instead of default lists of strings:
    values = CollectionField(collection_type=set, item_type=int)

排序和唯一性

class SortedUniqueTextList(models.Model):
    # Before saving, items will be sorted and duplicates dropped:
    texts = CollectionField(sort=True, unique_items=True)

选项和集合大小限制

class TaggedModel(models.Model):
    tags = CollectionField(
        # Both choices and max_items limit are checked during model validation.
        choices=(
            ('action', "Action"),
            ('comedy', "Comedy"),
            ('horror', "Horror"),
            # ...
        ),
        max_items=2
    )

get_FIELD_display 方法可以处理多个选项并提供自定义显示的选项

tagged_model = TaggedModel.objects.create(tags=['action', 'horror'])
tagged_model.get_tags_display()
"Action, Horror"

def li_mapper(value, label):
    return "<li>{0}</li>".format(label)

def ul_wrapper(field_display):
    return "<ul>{0}</ul>".format(field_display)

tagged_model.get_tags_display(delimiter='', mapper=li_mapper, wrapper=ul_wrapper)
'<ul><li>Action</li><li>Horror</li></ul>'

Django 内置验证器与整个字段值一起工作。 django-collectionfield 提供单个集合项的验证

from collectionfield.validators import (
    ItemMinValueValidator, ItemMaxValueValidator
)

class IntegerList(models.Model):
    values = CollectionField(
        item_type=int,
        # item validators check each item separately:
        validators=[ItemMinValueValidator(1), ItemMaxValueValidator(5)]
    )

表单字段

django-collectionfield 包含 2 个表单字段

from collectionfield.forms import CollectionField, CollectionChoiceField

# ``collectionfield.forms.CollectionField`` converts comma-separated text
# into collection of values:

class MyForm(forms.Form):
    values = CollectionField()

my_form = MyForm({'values': "A, B, C"})
my_form.is_valid()
True
my_form.cleaned_data['values']
['A', 'B', 'C']

# ``collectionfield.forms.CollectionChoiceField`` behaves more like
# regular MultipleChoiceField:

class MyChoiceForm(forms.Form):
   values = CollectionChoiceField(
       choices=(
           ('action', "Action"),
           ('comedy', "Comedy"),
           ('horror', "Horror"),
           # ...
       )
   )

my_choice_form = MyChoiceForm({'values': ['action', 'comedy']})
my_choice_form.is_valid()
True
my_choice_form.cleaned_data['values']
['action', 'comedy']

这两个表单字段支持与模型字段相同的参数集

from collectionfield.forms import CollectionField

class MyForm(forms.Form):
    values = CollectionField(collection_type=set, item_type=int)

my_form = MyForm({'values': "1, 2, 1, 3"})
my_form.is_valid()
True
my_form.cleaned_data['values']
{1, 2, 3}

数据库中的表示

CollectionField 将其值转换为最多 1024 个字符的字符串,格式如下

"|item1|item2|item3|"

默认分隔符(‘|’)和最大长度可配置

class MyModel(models.Model):
    values = CollectionField(delimiter="$", max_length=2000)

要求

Python:2.7、3.4、3.5

Django:1.8、1.9、1.10

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

django-collectionfield-0.0.4.tar.gz (15.7 kB 查看哈希值)

上传时间

构建分发

django_collectionfield-0.0.4-py2.py3-none-any.whl (20.0 kB 查看哈希值)

上传时间 Python 2 Python 3

由以下提供支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面