【问题标题】:I have a choice field on a model.py which allows the user to select a field value another model from within my sqlite database我在 model.py 上有一个选择字段,它允许用户从我的 sqlite 数据库中选择另一个模型的字段值
【发布时间】:2015-07-15 05:15:54
【问题描述】:

我在 model.py 上有一个选择字段,它允许用户从我的 sqlite 数据库中的另一个模型中选择一个字段值。使用开发服务器(“python manage.py runserver”命令选择字段已正确填充)在 runserver 命令期间填充。我遇到的问题是,当我们添加新字段时,我希望选择字段自动更新。

class UserData(models.Model):
    usertype = models.IntegerField('User Type',choices=((0, ("Boat Owner")),(1, ("Boat Manager")),(2, ("Travel Agent"))))
    username   = models.CharField(max_length=200,unique=True)
    password   = models.CharField(max_length=200)
    name       = models.CharField(max_length=200,verbose_name='Name')
    boat_no    = models.CharField(max_length=200,unique=True)
    address    = models.CharField(max_length=200)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone = models.IntegerField(validators=[phone_regex], blank=True) # validators should be a list
    email      = models.EmailField('email address', unique=True)
    avatar     = models.ImageField('profile picture', upload_to='images', null=True, blank=True)

    def image_img(self):
        if self.avatar:
            return u'<img src="/media/%s" width="50px" height="50px"/>' % self.avatar
        else:
            return 'NO IMAGES FOUND !'
     image_img.short_description = 'Thumb'
     image_img.allow_tags = True

    def __str__(self):
        return u'%s %s %s %s %s %s %s %s %s' % (self.edit,self.usertype,self.id,self.name,self.boat_no,self.username,self.password,self.address,self.email)

    class Meta:
        verbose_name = "Boat App User"
        verbose_name_plural = "Boat App User"

#Boat_Detail Module
class Boat_Detail(models.Model):
    BOAT_NUMBER = list ( (obj.boat_no,obj.boat_no) for obj in UserData.objects.all() )
    boat_no = models.CharField(max_length=200, choices=BOAT_NUMBER,verbose_name="Boat NUMBER")
    boat_name       = models.CharField(max_length=200)
    no_of_ac_rooms  = models.IntegerField(verbose_name="No of AC Rooms")
    no_of_nonac_rooms = models.IntegerField(verbose_name="No of Non AC Rooms")
    BOAT_MANAGER_LIST = list ( (obj.name,obj.name) for obj in UserData.objects.all() )
    BOAT_OWNER_LIST = list ( (obj.name,obj.name) for obj in UserData.objects.all() )
    boat_owner      = models.CharField(max_length=200, choices=BOAT_OWNER_LIST,verbose_name="Boat Owner")
    boat_manager    = models.CharField(max_length=200, choices=BOAT_MANAGER_LIST,verbose_name="Boat Manager")
    avatar          = models.ImageField('profile picture', upload_to='images', null=True, blank=True)

    def __str__(self):
        return u'%s %s %s %s %s %s' % (self.edit,self.id,self.boat_name,self.boat_no,self.boat_manager,self.boat_owner)

    class Meta:
        verbose_name = "Boat Details"
        verbose_name_plural = "Boat Details"

    def image_img(self):
        if self.avatar:
            return u'<img src ="/media/%s" width="50px" height="50px"/>' % self.avatar
        else:
            return 'NO IMAGES FOUND !'
    image_img.short_description = 'Thumb'
    image_img.allow_tags = True

【问题讨论】:

  • 您能否请edit您的问题是实际代码,并在80个字符左右插入一些换行符以提高可读性?
  • ForeignKey 不是你可以使用的吗?

标签: python django sqlite


【解决方案1】:

不幸的是,传递给模型字段的“choices=”参数与您的数据库迁移相关联。换句话说,每次添加到选项列表时都必须调用 manage.py makemigrations / migrate。

要解决此问题,您必须使用您的选择创建一个 Enum 并在您的模型之外对其进行管理。如果您使用的是 Python 2,请使用 backport 模块 enum34。要让 Enum.choices 返回字符串,请像这样子类化 Enum:

class ChoiceEnum(Enum):
    @classmethod
    def choices(cls):
        # get all members of the class
        members = inspect.getmembers(cls, lambda m: not (inspect.isroutine(m)))
        # filter down to just properties
        props = [m for m in members if not (m[0][:2] == '__')]
        # format into django choice tuple
        choices = tuple([(str(p[1].value), p[0]) for p in props])
        return choices

然后,不要在模型级别指定选项,而是在 ModelForm 中使用自定义字段。

usertype = forms.TypedChoiceField(choices=MyEnum.choices(), coerce=str) 

【讨论】:

  • 嗨...不管你说什么都是正确的...但是在model.py中...不使用form ....,所以有什么想法可以在model.py中解决跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
相关资源
最近更新 更多