简体   繁体   English

Django 数据表和枚举

[英]Django datatable and enum

I have a campaign model as follows:我有一个活动模型如下:

id campaign    objective             platform
1  Hello Word  MOBILE_APP_ENGAGEMENT Facebook
2  Hi There    VIDEO_VIEWS_PREROLL   Twitter

Model:模型:

class Campaign(Model):
    id = models.TextField(primary_key=True)
    name = models.TextField(default="")
    objective = models.TextField(null=True)
    platform = enumfields.EnumField(Platform, max_length=10, null=True)

The campaign holds both Twitter and FB campaigns.该活动同时包含 Twitter 和 FB 活动。

The objective field was a free text, but I am not happy with it.目标字段是一个自由文本,但我对此并不满意。

I would like to create 2 different enums (enum34):我想创建 2 个不同的枚举 (enum34):

class FacebookObjective(Enum):
  MOBILE_APP_ENGAGEMENT
  MOBILE_APP_DOWNLOAD

class TwitterObjective(Enum):
  VIDEO_VIEWS_PREROLL
  TWEET_ENGAGEMENTS

and somehow use them on the same column.并以某种方式在同一列上使用它们。 but not sure how to do it.但不知道该怎么做。

I thought to use enum, because I need the other uses to use it easily in the code.我想使用枚举,因为我需要其他用途才能在代码中轻松使用它。 eg:例如:

TwitterObjective.VIDEO_VIEWS_PREROLL

As far as I know (which isn't much where Django is concerned), to make this work you'll need to use a single Enum per field.据我所知(这不是 Django 所关心的),要完成这项工作,您需要为每个字段使用一个Enum So in your case I would put the Twitter or FB designation in the name of the members:因此,在您的情况下,我会将 Twitter 或 FB 名称放在成员的名称中:

Class Objective(Enum):
    FB_MOBILE_APP_ENGAGEMENT
    FB_MOBILE_APP_DOWNLOAD
    TW_VIDEO_VIEWS_PREROLL
    TW_TWEET_ENGAGEMENTS

If you really want to use different Enum s you have a couple choices:如果你真的想使用不同的Enum你有几个选择:

  • use nested Enum classes (see https://stackoverflow.com/a/35886825/208880 )使用嵌套的Enum类(参见https://stackoverflow.com/a/35886825/208880
  • use two classes and have your implementation choose between them (which will require either embedding a FaceBook or Twitter code in the name, such as FB_ and TW_, or using unique names across the two Enum s so you can reverse the lookup when going from db to Python)使用两个类并让您的实现在它们之间进行选择(这将需要在名称中嵌入 FaceBook 或 Twitter 代码,例如 FB_ 和 TW_,或者在两个Enum使用唯一名称,以便您可以在从 db到 Python)

This answer may help with the details.这个答案可能有助于了解细节。

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

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