Python 在django模型中保存列表
我正在做一个网络项目,我对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
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集合