2
votes

I started to learn Django, my first programming experience.

I have next models:

class Region(models.Model):
    name = models.CharField(u'Region', max_length=254, unique=True)


class Organization(models.Model):
    name = models.TextField(u'Org_name')
    inn = models.CharField(u'INN', max_length=254)
    region = models.ForeignKey(
        Region,
        related_name='org_region',
        blank=True,
        null=True,
        on_delete=models.SET_NULL
        )

class Person(models.Model):
    region = models.ForeignKey(
        Region,
        related_name='p_region',
        blank=True,
        null=True,
        on_delete=models.SET_NULL
        )
    organization = models.ForeignKey(
        Organization,
        related_name='p_org',
        blank=True,
        null=True,
        on_delete=models.SET_NULL
        )
    inn = models.CharField(u'INN', max_length=254)

I need to be grouped by region organization in which there is at least one person. To get the QS of the organizations in which there is at least one person I've tried:

Organization.objects.filter(p_org__isnull=False).distinct()

But, however, because the ratio is OneToMany, is it right?

qs = Person.objects.filter(organization__isnull=False)
Organization.objects.filter(p_org__in=qs).distinct()

The result equals, but I'm not sure that the first version right.

>>> Organization.objects.filter(p_org__in=qs).distinct().filter(region__name__exact="Region1").count()
12

>>> for i in Organization.objects.filter(p_org__isnull=False).distinct().values('region__name').annotate(count_in_reg=Count('region__name')):
...     print i['region__name'], i['count_in_reg']

Region0 4
Region1 16
Region2 64
...
...

After distinct(), values() and annotate() don't work as I need. Where is my mistake, How do I get the correct QS uniq Organization, that have at least one person without district()
Thanks

1

1 Answers

0
votes

Since region is a ForeignKey to the Person model you can access the Person model via region. You might want to try this:

Organization.objects.filter(region__p_org__isnull=False).distinct()