[Answer]-Storing and then accessing a pair of coordinates

1👍

Out of the box, Django has no support for storing a list in a field. The only way to store multiple data against a single field is a ManyToMany relationship to another table… however, this seems a little overkill when all you’re really wanting to store is a list of two-integer tuples.

Have a look at the top answer on this question. It’s an implementation of a ListField for Django, that allows storing of basic Python types – i.e, a list of tuples.

This is an example of how that code may work (untested, adapting their ‘taking it for a spin example in that question’):

>>> from foo.models import Map, ListField
>>> map = Map()
>>> map.spawn_locations
[]
>>> map.spawn_locations = [(1, 1), (-1, 12), (24, 52)]
>>> map.spawn_locations
[(1, 1), (-1, 12), (24, 52)]
>>> f = ListField()
>>> f.get_prep_value(map.spawn_locations)
u'[(1, 1), (-1, 12), (24, 52)]'

Then, to choose a random place to spawn:

>>> import random
>>> random.choice(map.spawn_locations)
(24, 52)
>>> random.choice(map.spawn_locations)
(1, 1)
👤Ben

Leave a comment