Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support base class relations and reverse for proxy models #1380

Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions graphene_django/tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,14 @@ class Meta:

objects = CNNReporterManager()

class APNewsReporter(Reporter):
"""
This class only inherits from Reporter for testing multi table inheritence
similar to what you'd see in django-polymorphic
"""
alias = models.CharField(max_length=30)
objects = models.Manager()


class Article(models.Model):
headline = models.CharField(max_length=100)
Expand Down
144 changes: 143 additions & 1 deletion graphene_django/tests/test_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from ..fields import DjangoConnectionField
from ..types import DjangoObjectType
from ..utils import DJANGO_FILTER_INSTALLED
from .models import Article, CNNReporter, Film, FilmDetails, Person, Pet, Reporter
from .models import Article, CNNReporter, Film, FilmDetails, Person, Pet, Reporter, APNewsReporter


def test_should_query_only_fields():
Expand Down Expand Up @@ -1067,6 +1067,148 @@ class Query(graphene.ObjectType):
assert result.data == expected


def test_model_inheritance_support_reverse_relationships():
"""
This test asserts that we can query reverse relationships for all Reporters and proxied Reporters and multi table Reporters.
"""

class FilmType(DjangoObjectType):
class Meta:
model = Film
fields = "__all__"

class ReporterType(DjangoObjectType):
class Meta:
model = Reporter
interfaces = (Node,)
use_connection = True
fields = "__all__"

class CNNReporterType(DjangoObjectType):
class Meta:
model = CNNReporter
interfaces = (Node,)
use_connection = True
fields = "__all__"

class APNewsReporterType(DjangoObjectType):
class Meta:
model = APNewsReporter
interfaces = (Node,)
use_connection = True
fields = "__all__"

film = Film.objects.create(genre="do")

reporter = Reporter.objects.create(
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
)

cnn_reporter = CNNReporter.objects.create(
first_name="Some",
last_name="Guy",
email="someguy@cnn.com",
a_choice=1,
reporter_type=2, # set this guy to be CNN
)

ap_news_reporter = APNewsReporter.objects.create(
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
)

film.reporters.add(cnn_reporter, ap_news_reporter)
film.save()

class Query(graphene.ObjectType):
all_reporters = DjangoConnectionField(ReporterType)
cnn_reporters = DjangoConnectionField(CNNReporterType)
ap_news_reporters = DjangoConnectionField(APNewsReporterType)

schema = graphene.Schema(query=Query)
query = """
query ProxyModelQuery {
allReporters {
edges {
node {
id
films {
id
}
}
}
}
cnnReporters {
edges {
node {
id
films {
id
}
}
}
}
apNewsReporters {
edges {
node {
id
films {
id
}
}
}
}
}
"""

expected = {
"allReporters": {
"edges": [
{
"node": {
"id": to_global_id("ReporterType", reporter.id),
"films": [],
},
},
{
"node": {
"id": to_global_id("ReporterType", cnn_reporter.id),
"films": [{"id": f"{film.id}"}],
},
},
{
"node": {
"id": to_global_id("ReporterType", ap_news_reporter.id),
"films": [{"id": f"{film.id}"}],
},
},
]
},
"cnnReporters": {
"edges": [
{
"node": {
"id": to_global_id("CNNReporterType", cnn_reporter.id),
"films": [{"id": f"{film.id}"}],
}
}
]
},
"apNewsReporters": {
"edges": [
{
"node": {
"id": to_global_id("APNewsReporterType", ap_news_reporter.id),
"films": [{"id": f"{film.id}"}],
}
}
]
},
}

result = schema.execute(query)
assert result.data == expected


def test_should_resolve_get_queryset_connectionfields():
reporter_1 = Reporter.objects.create(
first_name="John", last_name="Doe", email="johndoe@example.com", a_choice=1
Expand Down
4 changes: 2 additions & 2 deletions graphene_django/tests/test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class Meta:
fields = "__all__"

fields = list(ReporterType2._meta.fields.keys())
assert fields[:-2] == [
assert fields[:-3] == [
"id",
"first_name",
"last_name",
Expand All @@ -43,7 +43,7 @@ class Meta:
"reporter_type",
]

assert sorted(fields[-2:]) == ["articles", "films"]
assert sorted(fields[-3:]) == ["apnewsreporter", "articles", "films"]


def test_should_map_only_few_fields():
Expand Down
4 changes: 2 additions & 2 deletions graphene_django/tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def test_django_get_node(get):
def test_django_objecttype_map_correct_fields():
fields = Reporter._meta.fields
fields = list(fields.keys())
assert fields[:-2] == [
assert fields[:-3] == [
"id",
"first_name",
"last_name",
Expand All @@ -76,7 +76,7 @@ def test_django_objecttype_map_correct_fields():
"a_choice",
"reporter_type",
]
assert sorted(fields[-2:]) == ["articles", "films"]
assert sorted(fields[-3:]) == ["apnewsreporter", "articles", "films"]


def test_django_objecttype_with_node_have_correct_fields():
Expand Down
12 changes: 10 additions & 2 deletions graphene_django/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
from django.utils.translation import gettext_lazy
from unittest.mock import patch

from ..utils import camelize, get_model_fields, GraphQLTestCase
from .models import Film, Reporter
from ..utils import camelize, get_model_fields, get_reverse_fields, GraphQLTestCase
from .models import Film, Reporter, CNNReporter, APNewsReporter
from ..utils.testing import graphql_query


Expand All @@ -19,6 +19,14 @@ def test_get_model_fields_no_duplication():
assert len(film_fields) == len(film_name_set)


def test_get_reverse_fields_includes_proxied_models():
reporter_fields = get_reverse_fields(Reporter, [])
cnn_reporter_fields = get_reverse_fields(CNNReporter, [])
ap_news_reporter_fields = get_reverse_fields(APNewsReporter, [])

assert len(list(reporter_fields)) == len(list(cnn_reporter_fields)) == len(list(ap_news_reporter_fields))


def test_camelize():
assert camelize({}) == {}
assert camelize("value_a") == "value_a"
Expand Down
29 changes: 18 additions & 11 deletions graphene_django/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,24 @@ def camelize(data):


def get_reverse_fields(model, local_field_names):
for name, attr in model.__dict__.items():
# Don't duplicate any local fields
if name in local_field_names:
continue

# "rel" for FK and M2M relations and "related" for O2O Relations
related = getattr(attr, "rel", None) or getattr(attr, "related", None)
if isinstance(related, models.ManyToOneRel):
yield (name, related)
elif isinstance(related, models.ManyToManyRel) and not related.symmetrical:
yield (name, related)
model_ancestry = [model]

for base in model.__bases__:
if is_valid_django_model(base):
model_ancestry.append(base)

for _model in model_ancestry:
for name, attr in _model.__dict__.items():
# Don't duplicate any local fields
if name in local_field_names:
continue

# "rel" for FK and M2M relations and "related" for O2O Relations
related = getattr(attr, "rel", None) or getattr(attr, "related", None)
if isinstance(related, models.ManyToOneRel):
yield (name, related)
elif isinstance(related, models.ManyToManyRel) and not related.symmetrical:
Copy link
Collaborator

@firaskafri firaskafri Jan 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@TomsOverBaghdad this being inside a loop for base classes will break relations in the case of m2m, I think its safer to isolate getting base fields in a different method as in this case ManyToManyRel is two sided, in the case of A it is ManyToManyRel.related while in the case of B(A) it is ManyToManyRel.field. Check this out

Try having the m2m field in the base class just like the example you mentioned in the comment, not a reverse relation

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something like this:

elif isinstance(related, models.ManyToManyRel) and not related.symmetrical:
    if _model is not model:
        yield (name, getattr(attr, "field", None))
        continue

But my preference would still be to get base models relations and reverse relations in a different method

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Heard! Good catch @firaskafri ! Let me know what you think of the changes I pushed. I separated out getting local fields and included the models ancestry similar to the reverse fields.

yield (name, related)


def maybe_queryset(value):
Expand Down