2015-04-05 14 views
0

嘗試從用戶添加多對多關係時出現以下錯誤。Django模型錯誤:可以使用此多對多關係之前的字段x

ValueError: "" needs to have a value for field "appuser" before this many-to-many relationship can be used.

這裏是我的東西,做...

> user = AppUser(email="[email protected]", password="password") 
> address = Address(name="test",address_line1="1") 
> user.address.add(address) 

用戶模型:

class AppUser(AbstractBaseUser): 
    email = models.EmailField(
     verbose_name='email address', 
     max_length=254, 
     unique=True, 
     db_index=True, 
    ) 
    address = models.ManyToManyField('users.Address', null=True, blank=True) 

地址型號:

class Address(Base): 
    name = models.CharField(max_length=255) 
    address_line1 = models.CharField('Address Line 1', max_length=100) 
    def __unicode__(self): 
     return self.name 

回答

2

您需要保存的對象然後創建它們之間的多對多關係。

user = AppUser(email="[email protected]", password="password") 
address = Address(name="test",address_line1="1") 
user.save() 
address.save() 
user.address.add(address) 

原因是,每多到多的關係字段存儲在保存兩個對象的ID的一個單獨的表及其數據。對象之間的關係是該表中的行。所以很明顯,對象首先需要有ID才能輸入關係。他們通過保存獲得ID。

相關問題