获得外键值(Get Foreign Key Value)

2019-07-04 05:59发布

我怎样才能获得外键值? 我有一个链接到一年,系列,发动机型号,机身风格,变速箱和传动系统......所有的外键一个共同的车型。 我想获得这些字段的值,我的应用程序,但我坚持,我怎么会去他们。 任何想法将不胜感激。

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)

Answer 1:

你需要实际的ID? 尝试类似my_vehicle_ref.series.id

另外,我希望你知道, series属性右边有真正的实例Series ,所以你可以访问任何它的属性,例如, my_vehicle_ref.series.model.model



文章来源: Get Foreign Key Value