kmartforshort
kmartforshort

Reputation: 67

Saving lists in django models

I'm working on a web project, and I'm still really new to Django and the idea behind models. Basically, I want to create accounts that allow each user to save a group of locations. Currently, I've created models for each location (which must be unique to the user) and each user:

class Location(models.Model):
    name = models.CharField(max_length=70)
    longitude = models.DecimalField(max_digits=7,decimal_places=4)
    latitude = models.DecimalField(max_digits=7,decimal_places=4)
    custDescription = models.CharField(max_length=500)
    custName = models.CharField(max_length=70)

    def __unicode__(self):
        return self.name
    (...)

class User(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    locations = []

    (...)

    def addLocation(self, Location):
        if (Location not in locations):
            self.locations += Location
        else:
            return None

    def removeLocation(self, Location):
        if (Location in locations):
            i = locations.index(Location)
            locations.remove(i)
        else:
            return None

Will django's models support the list that I use in User.locations and allow me to add or remove a Location to it? If not, advice on more effective methods would be greatly appreciated!

Upvotes: 2

Views: 439

Answers (2)

wastl
wastl

Reputation: 2641

Maybe you should take a look into the django docs

You would have to do something like that

class User(models.Model):
   #Your implementation of user

class Location(models.Model):
    #....
    user = models.ForeignKey(Location)

It is then possible to access the locations like this:

u = <some_query_for_a_user>
locations = u.location_set

Upvotes: 1

Silwest
Silwest

Reputation: 1620

You should use ManyToManyField:

class User(models.Model):
   username = models.CharField(max_length=32)
   password = models.CharField(max_length=32)
   locations = models.ManyToManyField(Location)

Check that in you admin, I believe that you were searching for that.

Upvotes: 1

Related Questions