Skip to content

Commit

Permalink
Fix: No longer throw an error with relationship fields by using the a…
Browse files Browse the repository at this point in the history
…ctual column instead of the name.
  • Loading branch information
hvdklauw authored and bmispelon committed May 21, 2024
1 parent a788022 commit 49d50c7
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/modelsubquery/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion testproject/testapp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from django.db import models
from django.db.models.functions import ExtractYear

from modelsubquery import ModelSubquery


Expand All @@ -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):
Expand Down
13 changes: 13 additions & 0 deletions testproject/testapp/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 49d50c7

Please sign in to comment.