0

I have 2 models:

import uuid
from django.db import models


class Country(models.Model):
    name = models.CharField(max_length=255, unique=True)

    def city_count(self):
        return self.city_set.count()

class City(models.Model):
    country = models.ForeignKey('country.Country', on_delete=models.CASCADE)
    name = models.CharField(max_length=255)

And 2 Schemas:

import graphene
from graphene_django.filter import DjangoFilterConnectionField

from core.utils import ExtendedDjangoObjectType

from .models import Country as CountryModel, City as CityModel


class Country(ExtendedDjangoObjectType):
    class Meta:
        model = CountryModel
        filter_fields = {
            'name': ['exact'],
            # 'city_count': ['exact'] => this does not work!
        }
        interfaces = (graphene.relay.Node, )

    city_count = graphene.Int()

    def resolve_city_count(self, info):
        return self.city_count()


class City(ExtendedDjangoObjectType):
    class Meta:
        model = CityModel
        filter_fields = ['name']
        interfaces = (graphene.relay.Node, )


class Query(graphene.ObjectType):
    country = graphene.relay.Node.Field(Country)
    countries = DjangoFilterConnectionField(Country)
    city = graphene.relay.Node.Field(City)
    cities = DjangoFilterConnectionField(City)

I can query the city_count on countries, but I can't seem to filter on it (exact, or gte greater than / lte less than)

i.e. this works:

{
  countries(first: 10) {
    edges {
      node {
        name
        cityCount
      }
    }
  }
}

but this doesn't:

{
  countries(cityCount: 5) {
    edges {
      node {
        name
        cityCount
      }
    }
  }
}

and triggers the following error:

TypeError at /api/graphql/
'Meta.fields' must not contain non-model field names: city_count

Any idea how I can filter/order on non-model fields?

damusnet
  • 4,320
  • 3
  • 25
  • 39
  • This [dup](https://stackoverflow.com/questions/1205375/filter-by-property) specifically mentions `properly`, but the same applicable here too. The `self.city_set.count()` is written in the Django level and the ***SQL filter*** doesn't aware of the same. – JPG Jan 03 '21 at 02:45
  • @JPG yeah, I understand how the model property is useless, but I was hoping there was a way to override the query beforehand to include the count. It is doable in the Admin, I just don't know how to do it with graphene-django. – damusnet Jan 03 '21 at 04:03
  • *"It is doable in the Admin"* Is it? I don't think the property methods are used there. – JPG Jan 03 '21 at 04:12
  • @JPG this is what I mean by doable in the Admin: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/sorting_calculated_fields.html – damusnet Jan 03 '21 at 20:18
  • You see, that example uses the `annotate()` method of QuerySet (which is already in the dup I have mentioned) and it is happening in the DB level – JPG Jan 04 '21 at 02:36

0 Answers0