鍍金池/ 問答/Python  數(shù)據(jù)庫/ Django中的models如何建立指向auth.User的外鍵?

Django中的models如何建立指向auth.User的外鍵?

我目前在做一個(gè)項(xiàng)目,有個(gè)保存用戶通知的model如下:

class usrMes(models.Model):
    fromuser=models.ForeignKey(User,on_delete=models.PROTECT,related_name='id')
    touser=models.ForeignKey(User,on_delete=models.PROTECT,related_name='id')
    subject=models.CharField(max_length=100)
    content=models.CharField(max_length=2000)
    meslevel=models.IntegerField(default=0)
    ts=models.IntegerField(default=0)
    status=models.IntegerField(default=1)#0:已讀; 1:未讀; 
    class Meta:
        db_table = 'dj_usermes'

現(xiàn)在每次runserver都會(huì)提示:

TypeError: Direct assignment to the reverse side of a related set is prohibited. Use id.set() instead.

經(jīng)過排查,即便是一個(gè)空的views.py也會(huì)引發(fā)該問題,于是懷疑models寫的不對(duì)。
完整報(bào)錯(cuò)信息如下:

root@mzy7****:~/****# python36 manage.py runserver 0:8**1
Performing system checks...

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f41172d8d90>
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
    self.check(display_num_errors=True)
  File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check
    include_deployment_checks=include_deployment_checks,
  File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks
    return checks.run_checks(**kwargs)
  File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/checks.py", line 74, in check_user_model
    if isinstance(cls().is_anonymous, MethodType):
  File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 480, in __init__
    _setattr(self, field.attname, val)
  File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 509, in __set__
    % self._get_set_deprecation_msg_params(),
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use id.set() instead.

嘗試百度解決但沒有搜索到任何有價(jià)值的資料。
請(qǐng)問大家有嘗試過用外鍵指向User嗎?這里為什么不能正常運(yùn)行?
Django版本2.0,Python3.6,Debian8.9 x64

回答
編輯回答
替身

應(yīng)該是你定義的related_name和User的id屬性發(fā)生了沖突.
如果你沒有給外鍵定義related_name屬性,那么反向引用的時(shí)候就是: User.usrMes_set.all()
你添加了related_name='id'后就成了: User.id.all(), 這樣就和調(diào)用id屬性User.id有沖突了.

另外對(duì)同一個(gè)model的兩個(gè)外鍵,related_name不能重名

2018年7月29日 06:32