How do I prevent a ManyToManyField('self') from linked an object to itself?

Posted by dyve on Stack Overflow See other posts from Stack Overflow or by dyve
Published on 2011-01-10T07:53:12Z Indexed on 2011/01/10 8:53 UTC
Read the original article Hit count: 301

Filed under:
|

Consider this model (simplified for this question):

class SecretAgentName(models.Model):
    name = models.CharField(max_length=100)
    aliases = ManyToManyField('self')

I have three names, "James Bond", "007" and "Jason Bourne". "James Bond" and "007" are aliases of each other.

This works exactly like I want it to, except for the fact that every instance can also be an alias of itself. This I want to prevent. So, there can be many SecretAgentNames, all can be aliases of each other as long as "James Bond" does not show up as an alias for "James Bond".

Can I prevent this in the model definition? If not, can I prevent it anywhere else, preferably so that the Django Admin understands it?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models