Okay, how would I do this?
class Example(models.Model): parent_example = models.ForeignKey(Example)
I want to have a model have a foreign key reference to itself. When I try to create this I get a django validation error that Example is not yet defined.
Self-referencing foreign keys are used to model nested relationships or recursive relationships. They work similar to how One to Many relationships. But as the name suggests, the model references itself. Self reference Foreignkey can be achived in two ways. class Employee(models.
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.
You should use
models.ForeignKey('self')
as mentioned here.
Yes, just do this:
class Example(models.Model): parent_example = models.ForeignKey('self')
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