Mikhail Khromov
Mikhail Khromov

Reputation: 165

How do I use arrays in Django models?

I have model of ShortURL, which contains some data.

I want to collect metadata on each redirect (ip, time, etc), so I need to add ArrayField (which will contain dictionaries) of some sort. Didn't find anything such in docs, what do I do?

models.py:

class ShortUrl(models.Model):
    full_url = models.URLField()
    time_created = models.DateTimeField(auto_now=True)

    # visits = {}
    # Field will contain many dictionaries like {'ip': '...', 'time': '...', 'meta': ...}

Upvotes: 0

Views: 108

Answers (1)

dxillar
dxillar

Reputation: 317

Since Django only supports relational databases, that is why you didn't find these kind of fields to store in. There is ArrayField support for PostgresSQL database which I wouldn't suggest as it works with PostgresSQL only. More details on ArrayField is here.

So the suggested approach is normalize the relation. You can separate metadata to different table, which will have ForeignKey relation to the ShortURL table.

class Metadata(models.Model):
    short_url = models.ForeignKey(ShortURL, ...)
    ip = ...
    time = ...
    ...

So now your each of the Array element will be represented by a Metadata row.

Upvotes: 1

Related Questions