Search code examples
djangomodelsforeign-key-relationship

Django Foreign Key Relations


I am trying to make relationship between two tables, Registered_Users and User_Connections, so that those who are registered can add others in their connection list(more like add friends). Following are contents from models.py:

class Registered_Users(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=10)

    def __unicode__(self):
        return self.email

class User_Connections(models.Model):
    email = models.EmailField(blank=True)
    connection_email = models.EmailField(blank=True)
    user_connection = models.ForeignKey(Registered_Users, null=True)

    def __unicode__(self):
        return self.connection_email

What I am trying to do is:

  1. get a registered user:

    ru = Registered_Users.objects.get(id=1)
    
  2. get this registered user's connections from User_Connection:

    uc = User_Connections.objects.filter(user_connection=ru)
    

Now how can I display user connections' email id from User_Connection and first_name for each user connection from Registered_Users.

Let me know if there's a better way to achieve this.

NOTE: user connections' email id will also be present in Registered_Users because all the email ids must be registered.

Appreciate any help. Thanks.


Solution

  • class RegisteredUser(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        email = models.EmailField(unique=True)
        password = models.CharField(max_length=10)
        connected_users = models.ManyToManyField('self', blank=True, symmetrical=False)
    
        def __unicode__(self):
            return self.email
    

    the api now looks like this:

    ru = RegisteredUser.objects.get(id=1)
    another_user = RegisteredUser.objects.get(email='name@example.com')
    ru.connected_users.add(another_user)
    uc = ru.connected_users.all()
    for user in uc:
        print user.first_name, user.last_name, user.email