Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在django模型中保存列表_Python_Django_Django Models_Database Table - Fatal编程技术网

Python 在django模型中保存列表

Python 在django模型中保存列表,python,django,django-models,database-table,Python,Django,Django Models,Database Table,我正在做一个网络项目,我对Django和模型背后的想法还是很陌生。基本上,我想创建允许每个用户保存一组位置的帐户。目前,我已经为每个位置(用户必须是唯一的)和每个用户创建了模型: class Location(models.Model): name = models.CharField(max_length=70) longitude = models.DecimalField(max_digits=7,decimal_places=4) latitude = model

我正在做一个网络项目,我对Django和模型背后的想法还是很陌生。基本上,我想创建允许每个用户保存一组位置的帐户。目前,我已经为每个位置(用户必须是唯一的)和每个用户创建了模型:

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

django的模型是否支持我在User.locations中使用的列表,并允许我向其中添加或删除位置?如果没有,建议更有效的方法将不胜感激

您应该使用ManyToManyField:

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

检查一下你的管理员,我相信你正在搜索它。

也许你应该看看

你得做点这样的事

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

class Location(models.Model):
    #....
    user = models.ForeignKey(Location)
然后可以访问如下位置:

u = <some_query_for_a_user>
locations = u.location_set
u=
位置=u.location\u集合