获得外键价值

时间:2009-09-01 13:14:55

标签: django foreign-keys

如何获取外键值?我有一个常见的车型,链接到年份,系列,发动机类型,车身风格,变速箱和传动系......所有这些都是外键。我想为我的应用程序获取这些字段的值,但我不知道如何去做它们。任何想法都将受到高度赞赏。

class Model(models.Model):

  model = models.CharField(max_length=15, blank=False)
  manufacturer = models.ForeignKey(Manufacturer)
  date_added = models.DateField()
  def __unicode__(self):
      name = ''+str(self.manufacturer)+" "+str(self.model)
      return name 


class Year(models.Model):

  ALPHA_NUMERIC_CHOICES = (
      ('1', 'Numeric'),
      ('A', 'Alphabetic'),
  )

  year = models.PositiveSmallIntegerField()
  position_7_char = models.CharField(max_length=1, choices=ALPHA_NUMERIC_CHOICES)
  position_10 = models.CharField(max_length=1, blank=False)

  def __unicode__(self):
      return unicode(self.year)


class Series(models.Model):

  series = models.CharField(max_length=20, blank=True)
  model = models.ForeignKey(Model)
  date_added = models.DateField()

  def __unicode__(self):
      name = str(self.model)+" "+str(self.series)
      return name


class CommonVehicle(models.Model):

  year = models.ForeignKey(Year)
  series = models.ForeignKey(Series)
  engine = models.ForeignKey(Engine)
  body_style = models.ForeignKey(BodyStyle)
  transmission = models.ForeignKey(Transmission)
  drive_train = models.ForeignKey(DriveTrain)

  def __unicode__(self):
      name = ''+str(self.year)+" "+str(self.series)
      return name


class Vehicle(models.Model):

  stock_number = models.CharField(max_length=6, blank=False)
  vin = models.CharField(max_length=17, blank=False)
  common_vehicle = models.ForeignKey(CommonVehicle)
  exterior_colour = models.ForeignKey(ExteriorColour)
  interior_colour = models.ForeignKey(InteriorColour)
  interior_type = models.ForeignKey(InteriorType)
  odometer_unit = models.ForeignKey(OdometerUnit)
  status = models.ForeignKey(Status)
  odometer_reading = models.PositiveIntegerField()
  selling_price = models.PositiveIntegerField()
  purchase_date = models.DateField()
  sales_description = models.CharField(max_length=60, blank=False)

  def __unicode__(self):
      return self.stock_numberodels.ForeignKey(CommonVehicle)

1 个答案:

答案 0 :(得分:3)

您需要实际身份证吗?尝试类似my_vehicle_ref.series.id的内容。

另外,我希望您知道series属性确实存在Series的实例,因此您可以访问其属性的任何,例如{{ 1}}。