1

Here i want to do is that ,i want to list all the person who didn't blocked me.Here in the table Blocked there is two columns name who and whose . In whose column i store the id of the person whom i blocked and in the who column i store my id. Now i want to do that, when the blocked person click on view-person button in my web page he cannot see profile of the person one who blocked him.

when i did this query blocked_list = Blocked.objects.filter(whose = user_id). Now i got the list of the persons who blocked me. Now i want to exclude all this person from this query total_profiles = persons.objects.all().exclude(blocked_list). How can i do this.

models.py

class persons(models.Model):
    full_name = models.CharField(max_length=200)


class blocked(models.Model):
    who = models.ForeignKey(persons)
    whose = models.IntegerField(null=True) 

views.py

def blocked(request): 
    blocked_list = Blocked.objects.filter(whose = user_id) 
    total_profiles = persons.objects.all().exclude(blocked_list)
    return render_to_response('profiles/view_all.html', {'total_profiles':total_profiles,'}, context_instance=RequestContext(request),) 

please correct the question if it is not correct.

Thameem
  • 3,426
  • 4
  • 26
  • 32

1 Answers1

1

You can try this:

total_profiles = persons.objects.all().exclude(id__in = blocked_list.values_list('id', flat=True))

It's untested, but adapted from this answer.

Some notes:

  • if persons has the default manager, you can omit all().
  • whose does not have an index, so it will become slow when your dataset gets big. You can use a ForeignKey field instead of an IntegerField
  • the common convention is to capitalize class names and to write model names in singular i.e. Person instead of persons
Community
  • 1
  • 1
Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75
  • How it will become slow , when dataset gets big.If you don't mind could you please explain because i am new to django and python.thanks@Daniel Hepper – Thameem Jan 29 '14 at 10:07
  • 1
    This is not really specific to Django. By default, an `IntegerField` does not have an index. Therefor the database has to compare `user_id` to all rows in the `blocked` table. That becomes slow when your dataset gets big (millions of rows). – Daniel Hepper Jan 29 '14 at 12:34
  • Ok.thanks a lot for your answer.Let me ask one more thing. If i make that whose column as a ForeignKey of User,How can i skip that database comparison.@Daniel Hepper – Thameem Jan 29 '14 at 15:22
  • 1
    Django automatically creates an index for a `ForeignKey` field. – Daniel Hepper Jan 29 '14 at 15:39