I built a model called bbs with a reference to User table.
class Bbs_User(models.Model):
sid = models.AutoField(primary_key=True)
name = models.CharField(max_length=45)
#...
class Bbs(models.Model):
sid = models.AutoField(primary_key=True)
writer = models.ForeignKey(Bbs_User)
title = models.CharField(max_length=80)
content = models.TextField()
class Meta:
db_table = 'Bbs'
def __str__(self)
return self.title
In mysql client, I have look into Bbs table layout.
mysql> desc Bbs
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| sid | int(11) | NO | PRI | NULL | auto_increment |
| writer_id | int(11) | NO | MUL | NULL | |
At this point, I want to know why the field name is 'writer_id'.
I think the field name must be 'writer_sid' or 'writer'.
How can I fix it?
Just add str function in your foreign reference model Product.
Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.
Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
Foreign Keys are automatically named that way by the framework, but you can change the name of the column using db_column
parameter when declaring the field:
myKey = models.ForeignKey('MyRelatedModel', db_column='my_column_name')
Update: I should mention that the automatic naming has some advantages when making queries: if you call myBbsInstance.writer.id
you would get a RelatedManager instance that you need to resolve, hitting the database, to just getting the id, while calling myBbsInstance.writer_id
just return the number inserted in the column, without a database hit. It's very mnemonic.
By default, Django populates column's name by appending _id
to the field name you define in your model. You must explicitly specify column's name using db_column
property as follows:
writer = models.ForeignKey(Bbs_User, db_column='writer_sid')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With