代码之家  ›  专栏  ›  技术社区  ›  Christian

在django数据库中存储整数数组

  •  8
  • Christian  · 技术社区  · 16 年前

    在django数据库中存储整数数组的最佳方法是什么?

    5 回复  |  直到 6 年前
        1
  •  4
  •   Christian    6 年前

    CommaSeparatedIntergerField 自Django 1.9以后不再提供:

    From Docs :

    自1.9版以来已弃用:此字段已弃用,取而代之的是 CharField 使用validators=[验证逗号分隔的整数列表]。


    默认情况下,它设置一个逗号分隔的整数列表字段。

    int_list_validator

    返回一个regexvalidator实例,该实例确保字符串由 用sep分隔的整数。当 允许阴性为真。

    from django.db import models
    from django.core.validators import int_list_validator
    
    
    class YourModel(models.Model):
        ....
        ....
        int_list = models.CharField(validators=int_list_validator)   
        ....
    
        2
  •  9
  •   ayaz    16 年前

    CommaSeparatedIntegerField 立刻想到。其实施方式为 VARCHAR 在大多数数据库后端。当然,你可能想浏览一下 django/db/backends/* .

        3
  •  6
  •   Community CDub    8 年前

    this answer 有关commaseparatedintegerfield的可能替代版本的描述,它将为您做更多的工作(从列表转换为字符串并返回)。也许你可以和那个人联系一下,看看他是否已经写过了——)

        4
  •  3
  •   vdboor    13 年前

    如果您使用的是PostgreSQL,那么就可以本机存储数组类型。

    例如,请参见: https://github.com/aino/django-arrayfields https://github.com/ecometrica/django-dbarray

        5
  •  0
  •   spedy    7 年前

    我用的是arrayfield: https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/fields/#querying-arrayfield

    如。

    class Place(models.Model):
        nearby_places_ids = ArrayField(models.IntegerField(null=True, blank=True), null=True, blank=True)
    

    用法:

    place.nearby_places_ids = [1,2,3]
    place.save()
    
    models.Place.objects.filter(nearby_places_ids__contains=[1])
    <QuerySet [<Place: Hostel DIC>]>
    
    models.Place.objects.filter(nearby_places_ids__contains=[1,2,3,4])
    <QuerySet []>
    
    推荐文章