[Django]-Repeated fields in django models

3πŸ‘

βœ…

It’s hard to say definitively without a concrete example of what your doing, but generally, if you find yourself repeating a field, then it’s a clear sign for a one-to-many or many-to-many relationship, instead:

One-to-Many

class Field(models.Model):
    m = models.ForeignKey(M, related_name='fields')
    field = models.NullBooleanField()

Many-to-Many

class Field(models.Model):
    field = models.NullBooleanField()

class M(models.Model):
    fields = models.ManyToManyField(Field)
πŸ‘€Chris Pratt

1πŸ‘

Django models have an add_to_class method you could (ab)use for monkey-patching models the way you would like to do.

for i in range(1, 10):
    M.add_to_class('field_%s' % s, NullBooleanField())

0πŸ‘

It sounds like you are looking to have an EAV style database. You should try a library instead of rolling your own. To that end, Django EAV looks pretty awesome. https://github.com/mvpdev/django-eav

To read more about pros and cons of a bunch of libraries to accomplish this check out: https://stackoverflow.com/a/7934577/884453

Leave a comment