How to delete the first name and last name columns in django user model?

落花浮王杯 提交于 2021-01-28 10:51:34

问题


I created a custom user model just like the docs said, when I ran the makemigrations I went to the folder of migrations and deleted the first name and last name columns inside the 0001_initial.py and then I ran the migrate command, but when I ran the createsuperuser command it throwed an error in the terminal that django.db.utils.OperationalError: no such column: myapp_usermodel.first_name

How can I fix this? I want to delete the first name and last name columns because I'm not using them

EDIT: this is the user model

from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import AbstractUser

# Create your models here.
class usermodel(AbstractUser):
    email = models.EmailField(max_length=60)
    username = models.CharField(max_length=20, unique=True)
    password = models.CharField(max_length=20)
    
    def __str__(self):
        return self.username

回答1:


I went to the folder of migrations and deleted the first name and last name columns inside the 0001_initial.py

You shouldn't do that. This will indeed prevent Django from creating the columns. But now it will each time query under the impression that the columns are there. Furthermore if you make migrations again, it will try to add extra columns.

You should simply use the method resolution order (MRO) and set the field to None:

class usermodel(AbstractUser):
    first_name = None
    last_name = None
    
    def __str__(self):
        return self.username

You probably also better remove the table in the database and the migration file and make migrations again, and migrate the database.



来源:https://stackoverflow.com/questions/64391320/how-to-delete-the-first-name-and-last-name-columns-in-django-user-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!