0

I'm trying to provide for users possibility to store in SomeModel a list of ExtraParameters of any number or kind (it may be something small like IntegerField, BooleanField or quite large like TextField).

I tried to implement ExtraParameter abstract model class, that will keep ForeignKey to SomeModel, and also its child classes with only one parameter like:

class ExtraParameter(models.Model):
    somemodel = models.ForeignKey(SomeModel, ...)

    class Meta:
        abstract = True

class IntegerExtraParameter(ExtraParameter):
    value = models.IntegerField()

I believe it takes multiple small classes like this one so it could be migrated to multiple database tables of different fields.

Am I right? Please provide better solution. Maybe other way to decorate ExtraParameter is possible?

The problem with this approach is while implementing template it is not so easy to get all the stored parameters of all kind by doing somemodel.extraparameters.all(), rather I need to call every child class explicitly and build set from it. But also I've seen a solution with finding all subclasses of any class inside app's config, so it would help.

Jakub

Jacob
  • 109
  • 2
  • 11

1 Answers1

1

I think the answer you are looking for is covered in great depth in here:
https://stackoverflow.com/a/7934577/

Personally I like the way Django and JsonField works together.
https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.JSONField
JsonField would give you vast flexibility with dynamic metadata.

In this example I'm simply attaching a JsonField to those models that are in need of dynamic meta data. extra_information could then hold data about what kind of values is in relation with the parent model.

class ExtraInformationModel(models.Model):
    # Abstract model that adds json field for additional meta data

    extra_information = JSONField()

    class Meta:
        abstract = True


class SomeModel(ExtraInformationModel):
    # extra_information field comes from the abstract model
    
    ...usual model stuff..

Making queries with JsonFields is as easy as using Django orm usually is.
https://docs.djangoproject.com/en/3.1/topics/db/queries/#querying-jsonfield

(example from Django documentation)

   Dog.objects.create(name='Rufus', data={
       'breed': 'labrador',
       'owner': {
           'name': 'Bob',
           'other_pets': [{
               'name': 'Fishy',
           }],
       },
   })
   Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': None})
   Dog.objects.filter(data__breed='collie')