W1ldPo1nter / django-queryable-properties

Write Django model properties that can be used in database queries.
BSD 3-Clause "New" or "Revised" License
72 stars 1 forks source link

Models are not getting auto-annotated #10

Closed stefanofusai closed 11 months ago

stefanofusai commented 11 months ago

Hey, first of all thanks for your library. It solves many of my problems but unfortunately I'm not able to get it working

Here's a peek of what my model looks like:

class Lot(models.Model):
    ...
    lot_nr = models.TextField()
    ...

    @queryable_property
    def lot_nr_int(self) -> int:
        if self.lot_nr.isdigit():
            return int(self.lot_nr)

        else:
            return -1

    @lot_nr_int.annotater
    @classmethod
    def lot_nr_int(cls) -> models.IntegerField:
        return Case(
            When(lot_nr__regex=r"^\d+$", then=F("lot_nr")),
            default=Value(-1),
            output_field=models.IntegerField(),
        )

But doing something as simple as Lot.objects.all().order_by("lot_nr_int") results in the following error: FieldError: Cannot resolve keyword 'lot_nr_int' into field. Choices are: ..., lot_nr, ...

Which means, I guess, that the model isn't getting annotated correctly. Any idea of what I'm doing wrong? Thanks for the help.

stefanofusai commented 11 months ago

After digging in the docs I realized I was missing the magic line: objects = QueryablePropertiesManager() :)