I'm trying to use python's peewee library and create some foreign keys to associate two different Models. I'm reading through the peewee documentation here
where there are several points where the "related_name" attribute is used when creating a ForeignKeyField. It seems to follow a general pattern where the value of "related_name" is the plural form of the class you are creating (Tweet -> "tweets"). Is this value creating the name for the column in the table you're creating the ForeignKeyField in? How and why is this "related_name" attribute used?
I actually have never used peewee, but from the docs and my knowledge of the Django ORM (which looks a lot similar), here's what I can tell:
When you create a ForeignKeyField
, also the Model you refer to (the FK "destination") will be extended with a new attribute, that lets you access the relation "backwards".
In the example tutorial you linked, you can see that after the FK declaration, they can type user.tweets
, where the attribute tweets
takes the name you passed as the related_name
to the FK Field.
The reason why it is usually plural is that a ForeignKey defines a Many-to-One relationship, so the reverse will be One-to-Many: in the example, each Tweet has a FK to a User, and thus easch User will be allowed to have many tweets.