Django外键查询,为什么它返回None?
当我尝试使用get()查询外键时,我始终得到None
的值,尽管我知道它们在数据库中设置为1。我在这里错过了什么吗?我应该做一些不同的事情来获得外键值吗?Django外键查询,为什么它返回None?
下面的代码是什么样子:
class Car_to_brand(models.Model):
brand_id = models.ForeignKey(Brand, db_column='brand_id')
...
class Brand(models.Model):
(id is not defined here but it's the primary key)
...
print Car_to_brand.__dict__.get(brand_id)
这会给我{brand_id:None}
,但它应该是{brand_id:1}
。
问题是您已将您的字段命名为brand_id
而不是品牌。 get(brand_id)
正在返回None,因为那里的密钥brand_id
不在字典中。如果您打印car.__dict__
,则会看到它包含brand_id_id
。
但是,使用instance.__dict__.get()
来访问属性是非常不寻常的。尝试改为:
class Car(models.Model):
brand = models.ForeignKey(Brand) # don't need to set db_column, brand_id is the default
car.brand_id # this is the id of the brand (e.g. 1) that this car is linked to
car.brand # this is the brand instance
你不需要告诉Django如何完成它的工作。该字段对于外键不是“brand_id”,它只是“品牌”,因为虽然“Car”表(在我的示例中,我已经更名为您的模型)只有品牌的ID,当您解除引用时somecar.brand
Django会为您提供与其关联的品牌对象的实例。
class Car(models.Model):
brand = models.ForeignKey(Brand)
carname = models.TextField()
class Brand(models.Model):
brandname = models.TextField() # supplied for example
,创建一个汽车品牌之间的关系。这就是你需要的。
现在你可以说这样的话
car = Car.objects.get(carname = "Corvette")
print car.brand.brandname # prints "Chevrolet" unless your database is hosed.
print car.brand.id # prints the unique key Django uses to keep track of these relationships
至于你的榜样的最后一行,你想干什么? Car_to_brand
是描述数据库对象的类;它本身不是一个对象,所以它虽然描述了与品牌的关系,但它并没有自己的品牌。
清晰的有关最后一句有点。 Car_to_brand
是python对象,意思是python中的所有东西都是某种类型的对象,但它是一个Class对象,它描述了一个数据库表,它的访问器和关系。它不是一个Django数据库对象。
感谢您的帮助,澄清了Django的正确用法。 – Tickon
谢谢!你是对的,它包含brand_id_id而不是brand_id ...这是我的问题。 – Tickon
Alasdair:最后一行不应该是'car.brand.id'吗?汽车没有'brand_id'字段。 –
@Elf:不,我的意思是'car.brand_id'。也许我的'评论'不清楚,我试图澄清它。如果你有一个外键'car.brand',你可以用'car.brand_id'来访问这个ID。请参阅https://docs.djangoproject.com/en/dev/ref/models/fields/#database-representation。 'car.brand.id'会导致额外的查找django从db中获取品牌。 – Alasdair