views:

62

answers:

2

I want to have a model with a ManyToMany relationship with itself, I don't know how to write this but I'l try to write some code to illustrate what I want to do.

class Person(models.Model):
   name = models.CharField()
   occupation = models.CharField()

   fiends = models.ManyToManyField('self', through = PersonFiends)

My Model that I want the friends to go through

class PersonFriends(models.Model)
   ???
   comment = models.CharField()

In a manytomany field with through relationship if the other model's name was "Pet" for example I'd name my fiels in that through class 'person' and 'pet' and make them models. ForeignKey(Person) and Pet for example

What to I name my fields in my PersonFriends model for the two person-fields now that they are the same model?

+1  A: 
class PersonFriends(models.Model):
    from_person = models.ForeignKey(Person)
    to_person = models.ForeignKey(Person)

this is from db table structure of a ManyToMany relation to self from my Model structure. Django defines it like that..

FallenAngel
pretty certain you'd need "related_name" properties on those foreignkeys...
Gabriel Hurley
Gabriel Hurley is right, you need to define related_name, otherwise django will warn you. I get the model from sql table structure, so i forgot to add that, sorry.
FallenAngel
+3  A: 

You can do something like this:

class Person(models.Model):
    name = models.CharField(max_length = 255)
    occupation = models.CharField(max_length = 255)
    friends = models.ManyToManyField('self', through = 'PersonFriends', 
          symmetrical = False)
    #     ^^^^^^^^^^^
    # This has to be false when using `through` models. Or else your 
    # model will not validate.

class PersonFriends(models.Model):
    source = models.ForeignKey(Person, related_name = 'source')
    #                                  ^^^^^^^^^^^^
    # You need different `related_name` for each when you have 
    # multiple foreign keys to the same table. 

    target = models.ForeignKey(Person, related_name = 'target')
    comment = models.CharField(max_length = 255)
Manoj Govindan