我正在从事一个网络项目,但我对 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 中使用的列表并允许我向其中添加或删除位置?如果没有,将不胜感激关于更有效方法的建议!
请您参考如下方法:
也许你应该看看 django docs
你必须做类似的事情
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
