jeudi 28 septembre 2017

Defining more models in a decorator

I have a pattern that I'd like to make as reproducible as possible, it goes something like this:

class TranslatedThing(models.Model):
  name = models.Charfield(max_length=100)

class Thing(models.Model):
  translation = models.ForeignKey(TranslatedThing)
  name = models.Charfield(max_length=100)

The idea being that in my raw data I have some Things, which map to a reduced set of translated Things. Across many different data sets I have many different types of Things.

I already use an Abstract class to reduce the complexity of this pattern:

class AbstractThing(models.Model):
  name = models.CharField(max_length=100)

  class Meta:
    abstract = True

-------

class TranslatedThing(AbstractThing):
  pass

class Thing(AbstractThing):
  translated = models.ForeignKey(TranslatedThing)

But I'd like to automate the creation and linkage to TranslatedThing. Is this possible with a decorator? e.g.

@translate
class Thing(AbstractThing): pass

----

Thing.objects.filter(translation__name="foo") #works

I've read through but it looks like maybe not. Is there any other way to reduce the repetition of code while using this pattern?

Aucun commentaire:

Enregistrer un commentaire