1

In Django model, is it possible to have one field of that model as inline (as to have multiple instances of that field)? I can achieve this by creating an inline model and move that field there, but i'm trying to avoid TabularInline or StackedInline, and put them all together in one model.

Example of what i need is:

class Entity(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField(max_length=255)

and i need the ability to add multiple instances of "email" field, without creating new Inline model.

This is can be done using the below code (But that's what i'm trying to avoid):

class Entity(models.Model):
    name = models.CharField(max_length=255)

and Inline model:

class EntityEmail(models.Model):
    link = models.ForeignKey(Entity)
    email = models.EmailField(max_length=255)

2 Answers 2

2

Django 1.9 introduced support for the PostgreSQL field type ArrayField, which you could use for a list of strings (representing email addresses).

class Entity(models.Model):
    ...
    email_addresses = ArrayField(models.EmailField(max_length=200), blank=True)
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, Thanks @ian-price. currently i'm using MySQL, but since this only for PostgreSQL, i'll definitely move to it.
Django and PostgreSQL are definitely strong partners; if not tied to MySQL due to a legacy app then PGSQL offers a whole lot of benefits.
0

If there is a fixed number of fields, you can do this instead:

class Entity(models.Model):
    name = models.CharField(max_length=255)
    email_1 = models.EmailField(max_length=255)
    email_2 = models.EmailField(max_length=255)
    ...
    email_n = models.EmailField(max_length=255)

But if you don't know the number of fields in advance (or it's not the same for every Entity) then no, you'll have to use a separate model with a foreign key back to the Entity. (In the end, that's almost certainly a better design anyway.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.