Bob
Bob

Reputation: 8704

Model friends table in Django

I am trying to write a model for Contacts table (like on mobile phone) in Django.

My first idea was to create class Person which will have fields(name, phone, email, age, creation_date...), and to create class Contact that will have two fields (person1, person2). That means that person1 has person2 in contact list, but not vice versa.

But, now I read some more about Django, and I saw that I should better extend User model like this:

class Person(models.Model):
    user = models.OneToOneField(User)

And then I am not sure should I have Contact class, that will have 2 persons as I planned, or I should add one more field to Person class, like this:

class Person(models.Model):
    user = models.OneToOneField(User)
    contacts = models.ManyToManyField('self', related_name='contact_of', symmetrical=False)

What do you think, which approach is better / more correct?

Thanks!

Upvotes: 0

Views: 456

Answers (1)

cdvv7788
cdvv7788

Reputation: 2089

The approach with the ManyToMany field looks good enough. If you were to create another model to hold this manually you would need to add logic to avoid duplication (maybe other things too).

Also, with the ManyToMany you end up with users that have contacts...you can for example do this:

my_user.person.contacts.all()
my_user.person.contacts.add(another_user)
my_user.person.contacts.filter(phone='123456')

With the other approach you would need to run queries from Contact model:

Contact.objects.filter(user_1=pk1, user_2=pk2)
Contact.objects.create(user_1=pk1, user_2=pk2) # add logic or db constraints to prevent duplication

It is not that complicated, but the first one does make more sense for this case.

Upvotes: 1

Related Questions