Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

The Best way to Implement friendship is to use ManyToManyField in Django:

You can read more about it here: https://docs.djangoproject.com/en/1.6/ref/models/fields/#ref-manytomany

Also, to resolve you confusion about query, with 'uc' variable you can just do:

uc.email for email id and uc.user_connection.first_name for firstname .

You can read More about Django Queries and objects here : https://docs.djangoproject.com/en/1.6/topics/db/queries/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top