0

I have been noticing that I keep creating duplicated models that look exactly like this:

class Environment(m.Model):
    slug = m.SlugField(primary_key=True)
    name = m.CharField(max_length=32)

class Session(m.Model):
    environment = m.ForeignKey(Environment, on_delete=m.PROTECT)

They have a slug as a primary key and a char field and they are referenced from the other model with a foreignKey.

Would it be possible to create a custom field that automatically creates the new table with those 2 columns and sets a foreign key to it?

Sort of like:

class Session(m.Model):
    environment = m.SlugForeignKey()

I have been looking through the docs but all the custom fields I have seen talk about storing things in a column as oppose to a different table.

Any ideas how to do this?

Darkslave
  • 111
  • 5
  • You're probably looking for [model inheritence](https://docs.djangoproject.com/en/2.0/topics/db/models/#model-inheritance) – sytech Jan 17 '18 at 00:58
  • Possible duplicate of [Django: Creating a Mixin for Reusable Model Fields](https://stackoverflow.com/questions/6014282/django-creating-a-mixin-for-reusable-model-fields) – sytech Jan 17 '18 at 00:59

0 Answers0