简体   繁体   中英

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': ...}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM