简体   繁体   English

如何在Django模型中添加“set”数据类型?

[英]How do I add a 'set' datatype to a Django model?

This seems like such an obvious question that I'm absolutely certain it's been asked before, but unfortunately 'set' isn't a very good keyword for a search. 这似乎是一个显而易见的问题,我绝对肯定以前会被问过,但不幸的是'set'对搜索来说不是一个很好的关键词。

I'm trying to define a model that uses a 'set' datatype for one of it's member's -- think hours of the day and days of the week. 我正在尝试定义一个模型,该模型使用其中一个成员的'set'数据类型 - 想想当天的几小时和一周中的几天。 There's a very limited set of data that can be put in there, but you can select none or all of the possible values. 可以放入一组非常有限的数据,但您可以选择任何一个或所有可能的值。 Something might be allowed on any day of the week, just weekends, or anything in between. 一周中的任何一天,周末或两者之间的任何东西都可能被允许。 (Edit: Technically I could manage this through a many-to-many relationship and then adding the days of the week and hours of the day classes, but that seems rather absurd given that they're so heavily fixed. Making the client add hours of the day / days of the week to the system is silly, and they actually need to be fixed for consumers of relevant APIs to properly parse them) (编辑:从技术上讲,我可以通过多对多关系管理这个,然后添加一周中的日期和一天中的课时,但这似乎相当荒谬,因为它们已经如此严格修复。让客户增加小时数对于系统来说,一周中的一天/几天是愚蠢的,并且实际上需要为相关API的消费者修复它们以正确地解析它们)

But I can't figure out how to reproduce MySQLs 'set' datatype in Django. 但我无法弄清楚如何在Django中重现MySQL的'set'数据类型。

I approached the problem from the wrong direction, search wise. 我从错误的方向接近问题,搜索明智。 Instead of searching for a 'set' datatype (which is simply possible because 'set' is also used in the sense of 'set the variable to foo'), I needed to look up multiple select options. 而不是搜索'set'数据类型(这很简单,因为'set'也用于'将变量设置为foo'),我需要查找多个选择选项。

From there, there are plenty of references that point me to this code snippet, which is apparently the only option: 从那里,有很多引用指向我这个代码片段,这显然是唯一的选择:

http://djangosnippets.org/snippets/1200/ http://djangosnippets.org/snippets/1200/

This module implements ArrayField, which is pretty close to what you are after. 这个模块实现了ArrayField,它非常接近你所追求的。

https://github.com/niwibe/djorm-ext-pgarray https://github.com/niwibe/djorm-ext-pgarray

From the documentation: 从文档:

class Register(models.Model):
    name = models.CharField(max_length=200)
    points = ArrayField(dbtype="int")
    objects = ExpressionManager()

>>> Register.objects.create(points = [1,2,3,4])
<Register: Register object>

Here's how the ArrayField gets implemented: 以下是ArrayField的实现方式:

https://github.com/niwibe/djorm-ext-pgarray/blob/master/djorm_pgarray/fields.py https://github.com/niwibe/djorm-ext-pgarray/blob/master/djorm_pgarray/fields.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM