Gooman
Gooman

Reputation: 175

List of contacts for User

I have a UserProfile model, which extends User model:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.CharField(max_length=40, default='0')
    activation_key = models.CharField(max_length=40, blank=True)
    key_expires = models.DateTimeField(default=django.utils.timezone.now)

I want to make every user to have a list of contacts. Contact is an object of User model. I want to make list of contacts like in Skype or social network. I have tried to make in like this:

class UserContact(models.Model):
    user = models.ForeignKey(User, related_name='contacts')
    username = models.CharField(max_length=40, blank=True)

But I think that something is wrong. Because if I select everything from UserContact model, I receive the whole list of usernames, without ID's of users from User model.

Upvotes: 1

Views: 267

Answers (1)

Antoine Pinsard
Antoine Pinsard

Reputation: 35012

You should checkout Many-To-Many relationships.

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.CharField(max_length=40, default='0')
    activation_key = models.CharField(max_length=40, blank=True)
    key_expires = models.DateTimeField(default=django.utils.timezone.now)
    contacts = models.ManyToManyField(User)

Upvotes: 2

Related Questions