我对 Python/Django 相当陌生。 我想做的是单独存储汽车的描述,但同时我想标记(在 django admin 中)汽车描述,如下所示:
class CarDescription(models.Model):
length = models.IntegerField(max_length=10)
def __unicode__(self):
return "description of the car no %d" % (Car.id)
class Car(models.Model):
description = models.OneToOneField(CarDescription)
我知道 Car.id 那里是错误的(循环引用)。有什么办法可以解决吗?
最佳答案
您应该像这样构建模型:
class Car(models.Model):
# everything that has to do _only_ with a car
class CarDescription(models.Model):
car = models.ForeignKey(Car) # each description can belong to only one car
length = models.IntegerField(max_length=10)
# other fields that have only to do with a description
def __unicode__(self):
return unicode("description of the car no %d" % (self.car.pk))
Django 有一个非常好的 API 用于查找 related objects您应该完成此操作(完成 tutorial 后)。
关于Python/Django 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15593894/