python: model: can an attribute reference an attribute from the same model?
(this question will probably win the dumbiest question prize, but I'll give it a try)
I have a simple menu class in my models:
class Menu(models.Model):
name = models.CharField(null=False, blank=False,unique=True,max_length=50)
url = models.CharField(null=False, blank=False, unique=True,max_length=100)
sortOrder = models.IntegerField(null=False, blank=False, default=0)
this will happily let me build one level of menu items.
If I wanted to go further and add another level, how do I make an items reference and id from the same model and make sure this id is not the id of the same item?
so there are actually two questions:
1. how do I set the ForeignKey to and id from the same class? Referencing neither Me开发者_运维问答nu or self won't get validated:
class Menu(models.Model):
name = models.CharField(null=False, blank=False,unique=True,max_length=50)
url = models.CharField(null=False, blank=False, unique=True,max_length=100)
sortOrder = models.IntegerField(null=False, blank=False, default=0)
**parent = models.ForeignKey(Menu)**
will throw:
NameError: name 'Menu' is not defined
2. how do I make sure this item's id is not the id of this item?
Try self
parent = models.ForeignKey( 'self' )
精彩评论