0

I have a table called User which is defined like this:

IAM_CHOICES = (
    ('HomeOwner', 'HomeOwner'),
    ('Architect', 'Architect'),
    ('Interior Designer', 'Interior Designer'),
)

class User(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(_('First Name'), max_length=30, blank=True, null=True)
    middle_name = models.CharField(_('Middle Name'), max_length=30, blank=True, null=True)
    last_name = models.CharField(_('Last Name'), max_length=30, blank=True, null=True)
    about_yourself = models.TextField(null=True, blank=True)
    image = models.ImageField(upload_to=get_upload_path, null=True, blank=True)
    email = models.EmailField(_('Email Address'), unique=True,
        help_text=_('Please use your personal Email Address, not your Company or College'))
    address = models.TextField(null=True, blank=True)
    city = models.ForeignKey('common.City', null=True, blank=True)
    state = models.ForeignKey('common.State', null=True, blank=True)
    Iam = models.CharField(max_length=50, choices = IAM_CHOICES, null=True, blank=True)

and city table defined like this:

class City(models.Model):
    name = models.CharField(max_length=100)

How do i find city most users are from and are of certain Iam choice of ? i.e say for example find me the cities from where maximum architect (Iam choice type Architect) come from !

6
  • 1
    Try City.objects.filter(user__Iam='Architect').annotate(num_user=Count('user')).order_by('-num_user'). Commented Mar 13, 2014 at 10:43
  • oh !! thanks Bibhas.. good to hear from you .. :) Commented Mar 13, 2014 at 10:52
  • Same here. Did it work? Commented Mar 13, 2014 at 10:53
  • yes it did .. i din knew we can query like this.. :) Commented Mar 13, 2014 at 10:58
  • :) cool. will add it as an answer. Commented Mar 13, 2014 at 10:59

1 Answer 1

1

You can order the cities with maximum number of Architects like this -

City.objects.filter(user__Iam='Architect').annotate(num_user=Count('user')).orde‌​r_by('-num_user')

This first filters cities that have architects, then counts the architects and then order by them in descending order.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.