【问题标题】:Django populate choice from ForeignKeyDjango 从 ForeignKey 填充选择
【发布时间】:2014-03-20 19:13:05
【问题描述】:

在下面的代码中,我试图让 Owner 表单带有一个下拉菜单,其中包含 Car 模型中的汽车品牌作为选项。我确实得到了下拉菜单,但每个元素都列为“汽车对象”,而不是品牌。如何将 Car 模型中的品牌添加到菜单中?谢谢。

models.py

from django.db import models

class Car(models.Model):
    brand = models.CharField(max_length=20)

class Owner(models.Model):
    name = models.CharField(max_length=20)
    car_brand = models.ForeignKey(Car)

forms.py

from django.forms import ModelForm, ModelChoiceField
from app.models import Owner

class OwnerForm(ModelForm):
    car_brand = ModelChoiceField(queryset=Car.objects.all())

class Meta():
    model = Owner

【问题讨论】:

    标签: python django django-models django-forms foreign-keys


    【解决方案1】:

    __unicode__ 函数添加到您的模型定义中。

    class Car(models.Model):
        brand = models.CharField(max_length=20)
    
        def __unicode__(self):
            return u'%s' % (self.brand)
    

    这样您可以控制要显示的内容

    【讨论】:

      【解决方案2】:

      非常感谢您分享这个,它帮助了我!在 Django 1.8 中,尝试: 品牌 = 型号.ForeignKey(汽车)

      不要把car_放在外键前面

      【讨论】:

        猜你喜欢
        • 2022-11-12
        • 2014-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 2011-10-24
        相关资源
        最近更新 更多