1

I want to create field that hods list of emails. My model is like this :

class Alerts(models.Model):
    emails = MultiEmailField()
    events = models.OneToOneField(Event, on_delete=models.CASCADE)

All good, but when this models is saved in DB it is like this

{
"id": 11,
"emails": "['ht@ht.com,  bb@bb.com']",
"events": 13
}

The list in 'emails' key is represented as a string "['ht@ht.com, bb@bb.com']" , not as a list ['ht@ht.com, bb@bb.com']. I tried different method, parsers and approaches, but without success. Is there a way to save list in DB or not? If it is the second is there a way to receive back a list as a response, not a string, that is fine too. ( DB is MYSQL)

htodev
  • 85
  • 8
  • There is no data type in MySQL to store ***an array of items***. The `MultiEmailField` is a wrapper which helps you to save/store some data in list/array form. – JPG Aug 18 '20 at 14:37

4 Answers4

1

Django 3.1 added models.JsonField which can be used for all DB backends. You can use this to store a list

class Alerts(models.Model):
    emails = models.JsonField()
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
  • yeeah, that's fine, but we don't use this version in our project, it's not option for me – htodev Aug 18 '20 at 14:48
  • You can use JsonField as an external package https://pypi.org/project/django-jsonfield/ – Rarblack Aug 18 '20 at 15:18
  • I think that [`ListCharField`](https://django-mysql.readthedocs.io/en/latest/model_fields/list_fields.html#django_mysql.models.ListCharField) from `django-mysql` will be more suitable way in this case. – Timofey Katalnikov Aug 18 '20 at 15:23
0

You can just split the string to get the emails in a list like this:

email_list = emails.replace("['", "").replace("']", "").split(",  ")
dacx
  • 824
  • 1
  • 9
  • 18
0

You can use ListCharField from django-mysql lib.

from django.db import models
from django_mysql.models import ListCharField

class Alerts(models.Model):
    emails = ListCharField(
        base_field=models.EmailField(...),
        ...
    )
    events = models.OneToOneField(Event, on_delete=models.CASCADE)
0

Building on the answer of Dacx. And from https://stackoverflow.com/a/1894296/5731101

How about:

import ast

class Alerts(models.Model):
    raw_emails = MultiEmailField()
    events = models.OneToOneField(Event, on_delete=models.CASCADE)

    @property
    def emails(self):
        return ast.literal_eval(self.raw_emails)
S.D.
  • 2,486
  • 1
  • 16
  • 23