2017-05-17 42 views
0

我有以下型號:Django的1.11:無法獲取ManyToManyField工作

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」字段,也沒有數據庫中的數據透視表來保持多個關係。 ManyToMany有效載荷如何保存?

其次,我的目標是爲用戶提供多個地址。我希望用戶擁有多個「地址」(而不是每個地址都有一個用戶),因爲其他模型也可以擁有地址。我不希望地址模型與ForeignKeys有12個不同的「所有者」字段。

所以。我試試這個:

from myApp.models import User 
from myApp.models import Address 
user = User(email="[email protected]", 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") 

現在,我嘗試了address添加到user.addresses,我得到一個錯誤。

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' 

幫助?

回答

3

在多對多字段的定義之後,您將有一個多餘的逗號,將它變成一個元組。當你刪除它時,你會發現遷移將創建中間表,並且user.addresses.add()將起作用。

+0

我不能相信我錯過了。謝謝!那就是訣竅。 – JasonGenX