366👍
✅
You can pass in the name of a model as a string to ForeignKey and it will do the right thing.
So:
parent = models.ForeignKey("CategoryModel")
Or you can use the string “self”
parent = models.ForeignKey("self")
80👍
You can use the string ‘self’ to indicate a self-reference.
class CategoryModel(models.Model):
parent = models.ForeignKey('self')
https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
- [Django]-How to get an ImageField URL within a template?
- [Django]-Numeric for loop in Django templates
- [Django]-Can't compare naive and aware datetime.now() <= challenge.datetime_end
22👍
You also to set null=True
and blank=True
class CategoryModel(models.Model):
parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True)
null=True
, to allow in database
blank=True
, to allow in form validation
- [Django]-Django – {% csrf_token %} was used in a template, but the context did not provide the value
- [Django]-Has Django served an excess of 100k daily visits?
- [Django]-How to test auto_now_add in django
8👍
https://books.agiliq.com/projects/django-orm-cookbook/en/latest/self_fk.html
class Employee(models.Model):
manager = models.ForeignKey('self', on_delete=models.CASCADE)
OR
class Employee(models.Model):
manager = models.ForeignKey("app.Employee", on_delete=models.CASCADE)
https://stackabuse.com/recursive-model-relationships-in-django/
- [Django]-How do I reuse HTML snippets in a django view
- [Django]-How to resize an ImageField image before saving it in python Django model
- [Django]-How can I keep test data after Django tests complete?
Source:stackexchange.com