Home > OS >  Comparing between two user models
Comparing between two user models

Time:03-14

I have two models. UsersOne and UsersTwo. Both these databases looks like this:

class UsersOne(models.Model):
    username     = models.CharField(max_length=255, unique=True)
    firstname    = models.CharField(max_length=255, blank=True, null=True)
    lastname     = models.CharField(max_length=255, blank=True, null=True)
    password     = models.CharField(max_length=255)
    email        = models.CharField(max_length=255, blank=True, null=True)

I am tyring to find every user with matching email in the UsersTwo model that. So if there are 10 users in UsersOne and 5 of them have matching email UsersTwo i want to write them out in a csv file.

So for example if user John, Doe, ***, [email protected] also is a user in UserTwo model i want to make a query to get him.

So i have tried this.

import both models...

users_one = UsersOne.objects.all()

matching = []

for i in users_one:
     matching.append(UsersTwo.object.filter(email=users_one[i].email))

And i get this error:

QuerySet indices must be integers or slices, not User.`

CodePudding user response:

There are two problems: i is not an index, but a UserOne object, and by .append(…) you are adding the duplicates as an element, not as elements of the list.

You can solve this with:

matching = []
for user in UsersOne.objects.all()
     matching  = UsersTwo.object.filter(email=user.email)

But this is still inefficient: it will make a query for each item in UsersOne. You can boost efficiency with:

matching = UsersTwo.objects.filter(email__in=UserOne.objects.values('email'))

or for some databases, like , it is better to first materialize the list of values:

matching = UsersTwo.objects.filter(email__in=list(UserOne.objects.values_list('email', flat=True)))
  • Related