I’m experimenting with Django and I’m trying to figure out how to define a many to many relationship relating one entity to itself. Let’s say, for eg., I have a custom user object called “Myuser”. I want Myuser to have a list of friends that are also of type Myuser:
class Myuser(models.Model):
user = models.OneToOneField(User)
username = models.CharField(max_length=200)
last_login = DateTimeField(blank=True)
is_active = BooleanField(default=True)
birthday = models.DateField()
name = models.CharField(max_length=200)
friends = models.ManyToManyField(Myuser)
objects = MyuserManager()
def __init__(self, *args, **kwargs):
super(Myuser, self).__init__(*args, **kwargs)
self.myuser = self
def __unicode__(self):
return self.name
def is_authenticated(self):
return self.user.is_authenticated()
That won’t work because Myuser is not defined at the friends scope. So how would I define such a relationship?
Django has a special syntax for Many-to-many fields from a model to itself.
From the documentation, you would want to use something like this in your model:
In general, Django doesn’t have a problem with defining fields to models that are out of scope, or which haven’t been defined yet. The solution is to name the model with a string, and that name is resolved once the other model has been defined. This is necessary when defining two models that have foreign keys to one another, for instance.
'self'is a special case, though, for relationships back to the model which you are currently defining.