Python/Django 模型

标签 python django django-models

我对 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/

相关文章:

java - 在没有 API 的情况下创建软件界面

python - Django 使用多个数据库

Django-管理员中的UserProfile m2m字段-错误

django - 如何为Django模型Integerfield分配默认值,而相关的FormField是可选的?

python - Postgres+SQLAlchemy 在使用 default=func.now() 时将时间转换为 UTC

python - 绘制二维矩阵中特征的存在情况

python - 搜索python文件中的所有if条件并在下一行添加打印语句

java - 如何从 DJANGO 服务器获取和使用 HTTPResponse 消息

reactjs - React VS NextJS for Django

django - 我的 Django 网站中出现 SystemCheckError,为什么会出现这些中间件错误?