Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It's possible to use django mysql model array field

In my case I need design my model in array of fields expected.

{field 1: string, field 2: [""], field 3: [""] }

So far I designed my model like following:

class Collaborator(models.Model):
    name = models.CharField(max_length=50, blank=True, null = True, )

class Responsibility(models.Model):
    name = models.CharField(max_length=50, blank=True, null = True, )


class Class1(models.Model):
    field 1 = models.CharField(max_length=50, blank=True, null = True, )
    field 2 = models.ManyToManyField(Responsibility, related_name='res_cards', blank=True,null=True )
    field 3 = models.ManyToManyField(Collaborator, related_name='col_cards', blank=True, null=True )

So I am expecting for to get all fields in an array rather than define new model

like image 916
kubendiran k Avatar asked Feb 27 '26 07:02

kubendiran k


1 Answers

If you are using SQLite as your database, there is no alternative for ManyToManyField.

However, if you are using (or if you switch to) PostgreSQL as your database, you'll be able to use ArrayField.

You can use it like this:

field_1 = ArrayField(
            models.CharField(max_length=50, blank=True)
          )

P.S. I assume you aren't really going to name your fields field 1 etc., but if you do, don't use spaces, use underscores instead, so field_1, etc.

There is lots of information on how to use Postgres instead of SQLite, for instance this link would be a good start.

However, in most cases I would still recommend using a ManyToManyField, because it'll enable you to easily query on shared relationships between two objects, and prevent duplicate data as well.

like image 136
Nico Griffioen Avatar answered Mar 01 '26 21:03

Nico Griffioen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!