Django foreign key query, why it returns None?

巧了我就是萌 提交于 2021-01-28 05:23:13

问题


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?

Here's what the code looks like:

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 )

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


回答1:


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.

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



回答2:


You don't need to tell Django how to do its job. The field isn't "brand_id" for a foreign key, it's just "brand," because although the "Car" table (in my example below, I've renamed your model) only has the ID of the brand, when you dereference somecar.brand Django will hand you an instance of the brand object associated with it.

class Car(models.Model):
    brand = models.ForeignKey(Brand)
    carname = models.TextField()

class Brand(models.Model):
    brandname = models.TextField() # supplied for example

That creates a relationship between a car and its brand. That's all you need.

Now you can say things like

 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

As for the last line of your example, what are you trying to do? Car_to_brand is a class that describes a database object; it is not an object itself, and so while it describes a relationship to brand, it does not have a brand of its own.


A bit of clarity about that last sentence. Car_to_brand is a Python object in the sense that everything in python is an object of some sort, but it is a Class object that describes a database table, its accessors and relationships. It is not a Django database object.



来源:https://stackoverflow.com/questions/7276735/django-foreign-key-query-why-it-returns-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!