Django: In a ModelManager, how do I access a constant defined inside the related Model?

43 Views Asked by At

I have, for example, an Enum defined inside a Model. That model uses, and therefore imports, a ModeLManager.

In that ModelManager, I'd like to access the Enum that I defined inside the Model; but I can't import the Model there or I'd get a circular dependency error.

An example of the issue:

Managers.py

class CardManager(models.Manager):
    def spades(self):
        return self.filter(suit=2)

Models.py

from foo.managers import CardManager

class Card(models.Model):

    class Suit(models.IntegerChoices):
        DIAMOND = 1
        SPADE = 2
        HEART = 3
        CLUB = 4

    suit = models.IntegerField(choices=Suit.choices)
    objects = CardManager()

This code works perfectly well, but instead of having suit=2, I'd prefer to have something like suit=Card.Suit.SPADE. I can't find a way to make that reference work, though, as I can't import Card into Managers.py.

Should I be defining the enum inside the ModelManager instead of the Model? All examples I've come across define them in the Model instead.

1

There are 1 best solutions below

0
Marco On

You can define your manager directly in models.py or outsource your suit choices to another module e.g. choices.py.