From 49d50c7a64e153bf97c1a1a6b2edd41e477c5356 Mon Sep 17 00:00:00 2001 From: Harro van der Klauw Date: Tue, 14 May 2024 11:16:35 +0200 Subject: [PATCH] Fix: No longer throw an error with relationship fields by using the actual column instead of the name. --- src/modelsubquery/functions.py | 2 +- testproject/testapp/models.py | 4 +++- testproject/testapp/tests.py | 13 +++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/modelsubquery/functions.py b/src/modelsubquery/functions.py index 33652bc..1c8dbde 100644 --- a/src/modelsubquery/functions.py +++ b/src/modelsubquery/functions.py @@ -13,7 +13,7 @@ def _model_fields(model, fields): then return all the declared fields. """ # TODO: the pk/id field should always be returned - declared = {f.name for f in model._meta.get_fields()} + declared = {f.column for f in model._meta.get_fields()} if fields is None: return declared diff --git a/testproject/testapp/models.py b/testproject/testapp/models.py index 8451ee8..0760033 100644 --- a/testproject/testapp/models.py +++ b/testproject/testapp/models.py @@ -2,7 +2,6 @@ from django.db import models from django.db.models.functions import ExtractYear - from modelsubquery import ModelSubquery @@ -11,6 +10,9 @@ class Book(models.Model): rating = models.IntegerField(blank=True, null=True) published = models.DateField(default=date.today) has_cover = models.BooleanField(default=True) + author = models.ForeignKey( + "Person", on_delete=models.CASCADE, related_name="books", null=True + ) class PersonQuerySet(models.QuerySet): diff --git a/testproject/testapp/tests.py b/testproject/testapp/tests.py index 1954b6b..9871f24 100644 --- a/testproject/testapp/tests.py +++ b/testproject/testapp/tests.py @@ -79,3 +79,16 @@ def test_deffered_fields(self): self.assertEqual(person.book_of_year.title, "test") with self.assertNumQueries(1): self.assertEqual(person.book_of_year.rating, 5) + + def test_with_related_field(self): + author = baker.make(Person) + book = baker.make(Book, author=author) + + # Yes he wrote a book in his birthyear! ;-) + + person = Person.objects.with_book_of_the_year().get() + self.assertEqual(person.book_of_year, book) + + # The relation is there, but it's lazy! + with self.assertNumQueries(1): + self.assertEqual(person.book_of_year.author, author)