8π
β
It is common to add a foreign key to self as such:
class Item(models.Model):
parent = models.ForeignKey('self')
You may specify a related name as such:
class Item(models.Model):
parent = models.ForeignKey('self', related_name='children')
Because an Item may not have a parent, donβt forget null=True and blank=True as such:
class Item(models.Model):
parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
Then you will be able to query children as such:
item.children
You might as well use django-mptt and benefit of some optimization and extra tree features:
from mptt.models import MPTTModel, TreeForeignKey
class Item(MPTTModel):
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
π€jpic
0π
Yes, you can use ForeignKey to self. See https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
π€Niklas
- [Django]-Change field names in a Django query
- [Django]-Django redirect() with additional parameters
- [Django]-How can I rename an uploaded file on Django before sending it to amazon s3 bucket?
- [Django]-Is it possible to redirect the python output to web by using 'sys.stdout' command?
- [Django]-Custom widget not validating only the first time
-1π
You would use foregein key in the same model if and only if you use string.
class Item(models.Model):
foo = models.ForeignKey("reposted_from")
class reposted_from(models.Model):
repost_from = models.CharField(max_length=122)
for example.
Otherwise, you will get undefined reference.
Is that what you need?
π€CppLearner
Source:stackexchange.com