2012-10-30 84 views
10

我有這樣的錯誤:Django。此函數的無效關鍵字參數。多對多

'人' 是這個函數

class Passage(models.Model): 
    name= models.CharField(max_length = 255) 
    who = models.ForeignKey(UserProfil) 

class UserPassage(models.Model): 
    passage = models.ForeignKey(Passage) 
    people = models.ManyToManyField(UserProfil, null=True) 

class UserProfil(models.Model): 
    user = models.OneToOneField(User) 
    name = models.CharField(max_length=50) 

我嘗試了無效的關鍵字參數:

def join(request): 
    user = request.user 
    user_profil = UserProfil.objects.get(user=user) 
    passage = Passage.objects.get(id=2) 
    #line with error 
    up = UserPassage.objects.create(people= user_profil, passage=passage) 
    return render_to_response('thanks.html') 

怎樣一個人準確地做到這一點?謝謝!

回答

20

您需要保存/創建對象,然後才能添加ManyToMany關係:

up = UserPassage.objects.create(passage=passage) 
up.people.add(user_profil) 

ManyToMany關係未保存到你的表列。在這裏閱讀第一個回覆了很好的解釋:

Django ManyToMany field is not created in model

@DanielRoseman: Because a ManyToMany isn't a field, at least not one that exists as a database column. It's a relationship with a linking table. You'll find that a table named myapp_teacher_subjects has been created, with foreign keys to both teacher and subjects.

相關問題