Django外键查询,为什么返回None? [英] Django foreign key query, why it returns None?

查看:90
本文介绍了Django外键查询,为什么返回None?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用get()查询外键时,即使我知道在数据库中将它们设置为1,我也总是得到 None 值.我在这里想念什么吗?我应该做些其他事情来获取外键值吗?

When I try to query foreign keys using get(), I always get None values, even though I know they are set to 1 in the DB. Am I missing something here? Should I do something different to get the foreignkey values?

代码如下:

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} .

That would give me {brand_id:None}, but it should be {brand_id:1}.

推荐答案

问题是您已将字段命名为 brand_id 而不是brand. get(brand_id)返回None,因为字典中没有键 brand_id .如果打印 car .__ dict __ ,则会看到它包含 brand_id_id .

The problem is that you have named your field brand_id and not brand. get(brand_id) is returning None, because there the key brand_id is not in the dictionary. If you print car.__dict__, you will see that it contains brand_id_id instead.

但是,使用 instance .__ dict __.get() 访问属性是非常不寻常的.请尝试以下操作:

However, it is highly unusual to access attributes using instance.__dict__.get(). Try the following instead:

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外键查询,为什么返回None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆