如何在Django中以一种形式组合来自不同模型的字段?

时间:2018-09-05 03:53:06

标签: python django django-models django-forms

假设我有3个模型

class Products(models.Model):
    Brand= models.ForeignKey(City,models.CASCADE, related_name='city')
    Title = models.CharField(max_length=200, db_index=True)
    description = models.TextField(blank=True,max_length=250)
    price = models.DecimalField(max_digits=11, decimal_places=2)

class Clothes(models.Model):
    product = models.ForeignKey(Products,models.CASCADE, related_name='clothe')
    Color= models.CharField(max_length=200, db_index=True, unique=True)

class Smartphones(models.Model):
    product = models.ForeignKey(Products,models.CASCADE, related_name='phone')
    storage= models.DecimalField(max_digits=11, db_index=True)

我如何以一种形式组合来自不同模型的字段,以便我们可以得到这样的东西:

class ClothesForm(ModelForm):
  class Meta:
      model = Clothes
      fields = ('brand','Title','Color)

class PhonessForm(ModelForm):
  class Meta:
      model = Smartphones
      fields = ('brand','Title','storage')

如果可行,是否可以为每种形式分配品牌选择,例如:

  phones_Brand = (('Samsung','Samsung'),
  ('Iphon','Iphon'))

  clothes_Brand = (('Nike','Nike'),
  ('Adidas','Adidas'))

谢谢

0 个答案:

没有答案