ValueError: Related model 'myapp.ExUser' cannot be resolved django擴展User字段


擴展字段目前有兩種方法:

  1. 擴展字段 新建一張表->然后與原有表創建一對一關系
  2. 繼承django.contrib.auth.models下的AbstractUser類 ,重寫User

兩種方式都是官方文檔提到的,,實現方法可以在官網以及搜索引擎搜到各大佬的博客上,我今天只分享一下自己遇到的問題及解決方法

我采用的是第2種, 重寫User的方法,但是在遷移數據庫的時候,遇到問題,

編寫好其它表之后,發現User表中字段需要添加於是在models.py 文件中添加了 ExUser

from django.db import models
from django.contrib.auth.models import AbstractUser


class ExUser(AbstractUser):
    phone = models.CharField(max_length=11, unique=True, blank=True)

class Post(models.Model):
    .......

在settings.py文件中添加

AUTH_USER_MODEL = 'app.ExUser'

添加完成后執行python manage.py makemigrations 然后報錯

django.db.migrations.exceptions.CircularDependencyError: auth.0011_update_proxy_permissions, myqpp.0002_exuser_post

或者執行 python manage.py migrate 報錯

ValueError: Related model 'myapp.ExUser' cannot be resolved

然后開始各種查找資料,在官網的介紹中說

Changing to a custom user model mid-project

Changing AUTH_USER_MODEL after you've created database tables is significantly more difficult since it affects foreign keys and many-to-many relationships, for example.

This change can't be done automatically and requires manually fixing your schema, moving your data from the old user table, and possibly manually reapplying some migrations. See #25313 for an outline of the steps.

Due to limitations of Django's dynamic dependency feature for swappable models, the model referenced by AUTH_USER_MODEL must be created in the first migration of its app (usually called 0001_initial); otherwise, you'll have dependency issues.

In addition, you may run into a CircularDependencyError when running your migrations as Django won't be able to automatically break the dependency loop due to the dynamic dependency. If you see this error, you should break the loop by moving the models depended on by your user model into a second migration. (You can try making two normal models that have a ForeignKey to each other and seeing how makemigrations resolves that circular dependency if you want to see how it's usually done.)

大致的意思就是 項目寫到一半,修改自定義用戶模型,文中提到,在第一次創建數據庫的時候,最好就已經開始使用自定義用戶模型,否則等執行一次python manage.py makemigrations命令創建了0001_initial.py文件之后,,會形成一堆依賴關系,,想修改auth,就沒有自動化了,,只能手動修改,並且會動態依賴會成為循環.............總之一句話,不好改了

如果被逼無奈,,可以去嘗試 #25313,,里面提供了好多方法,可以一試.

我的選擇是,,直接刪庫,,並且把migrations 文件夾下的除了__init__.py之外的文件清空,,重新創建數據庫就行了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM