why data column shows as modelname object(1) when I refer foreign key? Django

Viewed 40

When I am trying to get data from the model the column which I refer foreign key shows as object(value). why not value alone?..

say for example in y model i am using foreign key of x model column (id). it showing as x object(1) instead of 1.

How to solve it?

1 Answers

A ForeignKey will lazily load the object it refers to, so if you have a ForeignKey named foo that refers to the Foo model, it does not return the primary key of that Foo object, but the Foo object itself.

In the column it will call the __str__ on that object, and the default for the __str__ is the name of the model, with between brackets the primary key, so ModelName(pk) with ModelName the name of the model, and pk the primary key of the object.

You can change this behavior by overriding the __str__ method, for example:

class Foo(models.Model):
    # …
    
    def __str__(self):
        return str(self.pk)

Where Foo is the class that is referenced by the ForeignKey, this is not (per se) the class where the ForeignKey is defined.

Usually __str__ however should not return the primary key, but for example the name of the object, or something similar.

If you want to use the value stored in the database as foreign key, you can use foo_id, with foo the name of the ForeignKey.

Related