gpt4 book ai didi

python - Django 模型中的动态选择字段

转载 作者:太空狗 更新时间:2023-10-29 17:15:06 25 4
gpt4 key购买 nike

我的模型.py:

SHOP1_CHOICES = (
('Food Court', 'Food Court'),
('KFC', 'KFC'),

)

SHOP2_CHOICES = (
('Sports Arena', 'Sports Arena'),
('Disco D', 'Disco D'),

)

SHOP3_CHOICES = (
('Bowling Arena', 'Bowling Arena'),
('Cinemax', 'Cinemax'),

)

class Feed(models.Model):
gender = models.CharField(max_length=5, choices=GENDER_CHOICES, default='girl')
name =models.CharField(max_length=25)
shop=models.CharField(max_length=20)
location=models.CharField(max_length=25, choices=SHOP1_CHOICES)

如果 Feed.shop == 'shop1' 我想在 Feed.location 上加载 SHOP1_CHOICES。目前不管是什么店,它都只显示SHOP1_CHOICES(不足为奇)。我该如何实现呢?我被卡住了,请帮忙。

最佳答案

这是我的方法:

我使用 lazy 来延迟加载:

from django.utils.functional import lazy

在这里,选择选项的助手:

def help_SHOP_CHOICES():
SHOP1_CHOICES = [
('Food Court', 'Food Court'),
('KFC', 'KFC'),
]
SHOP3_CHOICES = [
('Bowling Arena', 'Bowling Arena'),
('Cinemax', 'Cinemax'),
]
return random.choice( SHOP1_CHOICES + SHOP3_CHOICES ) # choose one

最后是动态选择的模型:

class Feed(models.Model):
...
location=models.CharField(max_length=25, choices=SHOP1_CHOICES)

def __init__(self, *args, **kwargs):
super(Feed, self).__init__(*args, **kwargs)
self._meta.get_field('location').choices = \
lazy(help_SHOP_CHOICES,list)()

关于python - Django 模型中的动态选择字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6001986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com