Django 1.11:Can';I don’我不能让很多地方工作
我有以下型号:Django 1.11:Can';I don’我不能让很多地方工作,django,django-models,Django,Django Models,我有以下型号: class Address(models.Model): address1 = models.CharField(max_length=150, null=True) address2 = models.CharField(max_length=150, null=True, blank=True) city = models.CharField(max_length=50, null=True) state_province = model
class Address(models.Model):
address1 = models.CharField(max_length=150, null=True)
address2 = models.CharField(max_length=150, null=True, blank=True)
city = models.CharField(max_length=50, null=True)
state_province = models.CharField(max_length=50, null=True)
zipcode = models.CharField(max_length=10, null=True)
country = models.CharField(max_length=3, default='USA', null=False)
created_at = models.DateTimeField(db_index=True, auto_now_add=True)
updated_at = models.DateTimeField(db_index=True, auto_now=True)
class Meta:
db_table = 'addresses'
而这个
class User(models.Model, AbstractBaseUser, PermissionsMixin):
email = models.EmailField(db_index=True, max_length=150, unique=True,
null=False)
first_name = models.CharField(max_length=45, null=False)
last_name = models.CharField(max_length=45, null=False)
mobile_phone = models.CharField(max_length=12, null=True)
profile_image = models.CharField(max_length=150, null=True)
is_staff = models.BooleanField(db_index=True, null=False, default=False)
is_active = models.BooleanField(
_('active'),
default=True,
db_index=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
addresses = models.ManyToManyField(Address),
USERNAME_FIELD = 'email'
objects = MyCustomUserManager()
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
class Meta:
db_table = 'users'
我的第一个谜团是,通过迁移模型,users表中没有“addresses”字段,数据库中也没有pivot表来保持多个关系。有多少有效载荷被保留
其次,我的目标是为用户提供多个地址。我希望用户有多个“地址”(而不是每个地址都有一个用户),因为其他模型也可以有地址。我不希望地址模型有12个不同的“所有者”字段和foreignkey
所以。我试试这个:
from myApp.models import User
from myApp.models import Address
user = User(email="test@test.com", first_name="john", last_name="doe", mobile_phone="444")
# the model permits partial address fields, don't worry about that.
address = Address(city="New York", zipcode="10014")
现在我尝试将地址
添加到用户.地址
中,我得到一个错误
user.addresses.add(address)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-0337af6b1cd4> in <module>()
----> 1 user.addresses.add(address)
AttributeError: 'tuple' object has no attribute 'add'
user.addresses.add(地址)
---------------------------------------------------------------------------
AttributeError回溯(最近一次呼叫上次)
在()
---->1.用户地址。添加(地址)
AttributeError:“tuple”对象没有属性“add”
帮助?在多对多字段的定义之后有一个多余的逗号,这会将其转换为元组。删除此项后,您将发现迁移将创建中间表,并且
user.addresses.add()
将起作用。在多对多字段的定义之后有一个多余的逗号,将其转换为元组。删除此项后,您将发现迁移将创建中间表,并且user.addresses.add()
将起作用