Django模型中的动态选择域

2024-06-06 11:26:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我的模特.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(毫不奇怪),我如何实现它?我卡住了,请帮忙。


Tags: foodmodelsfeedlengthmaxchoicescharfieldsports
3条回答

这是我的方法:

我使用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)()

我觉得你不应该在模特身上这样做,形式是个更好的地方。或者你应该重新考虑你的模式。例如:

class Location(models.Model):
    pass

class Shop(models.Model):
    location = models.ForeignKey(Location)

class Feed(models.Model):
     shop = models.ForeignKey()

来自Django文档:http://docs.djangoproject.com/en/dev/ref/models/fields/#choices

Finally, note that choices can be any iterable object -- not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever.

相关问题 更多 >