I want to know what the difference between these two foreignkey definitions are.
(1) MyFKField = models.ForeignKey('MyModel')
(2) MyFKField = models.ForeignKey(MyModel)
I understand (I think...) that (1) MyModel
needs to be defined in that same file and the other needs to be imported, but I'm unsure of the reason/benifits of doing it either way.
I had a look through the Django docs but couldnt find anything, and Im also not sure if this is the right place to ask, so apologies if not.
Cheers
What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.
The only difference between these two is that ForeignKey field consists of on_delete option along with a model's class because it's used for many-to-one relationships while on the other hand, the OneToOneField, only carries out a one-to-one relationship and requires only the model's class.
db_column. The name of the database column to use for this field.
Django docs states that you would use a string to (1):
model.ForeignKey('self')
)model.ForeignKey('app.mymodel')
)But in general, specifying the model class directly is clear where it's coming from (2).
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