Django ManyToManyField自行丢弃错误

时间:2015-06-06 21:41:47

标签: python django django-models

我正在尝试将ManyToManyField注册到自我对象,当我尝试访问包含客户端模型列表的页面时出现错误

'ManyRelatedManager' object has no attribute 'pk'

这就是我的模型的样子:

class Client(models.Model):
    user = models.OneToOneField(User)
    contacts = models.ManyToManyField('self',symmetrical=False,blank=True,through='Friends')

class Friends(models.Model):
    client = models.ForeignKey(Client)
    contact = models.ForeignKey(Client,related_name='contact')

我也尝试通过部分删除,所以就像这样:

class Client(models.Model):
        user = models.OneToOneField(User)
        contacts = models.ManyToManyField('self',symmetrical=False,blank=True)

我不太确定我做错了什么。我只是想注册可以附加多个客户端(联系人)的客户端。你能告诉我做错了什么吗?谢谢!

更新 - 追溯:

AttributeError at /client/
'ManyRelatedManager' object has no attribute 'pk'
Request Method: GET
Request URL:    http://127.0.0.1:8000/client/
Django Version: 1.8.2
Exception Type: AttributeError
Exception Value:    
'ManyRelatedManager' object has no attribute 'pk'
Exception Location: /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/rest_framework/relations.py in get_url, line 202
Python Executable:  /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4
Python Version: 3.4.3
Python Path:    
['/Users/bobandavidovic/PycharmProjects/myapp/myapp',
 '/Library/Frameworks/Python.framework/Versions/3.4/lib/python34.zip',
 '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4',
 '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin',
 '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages']
Server time:    Sun, 7 Jun 2015 00:00:39 +0200

更新 - 我正在使用Django Rest Framework

1 个答案:

答案 0 :(得分:1)

如果尝试将related_name参数添加到ManyToMany字段会发生什么。例如:

contacts = models.ManyToManyField('self', related_name='client', symmetrical=False, blank=True, through='Friends')