所以我试图有问题地创建实例,但我不断收到此错误。当我尝试makemigrations时,错误发生在最后一行rec.save()上。没有rec.save()行,它工作正常。 我已经尝试过Users.objects.create_user(username =“xy”,password =“password123”),并且还刷新了取出rec.save()行的数据库。
django.db.utils.IntegrityError:NOT NULL约束失败:catalog_company.modif ied_by_id
这是我的代码
from django.db import models
from django.contrib.auth.models import User, UserManager
from datetime import date
import datetime
from django.urls import reverse #Used to generate URLs by reversing the URL
patterns
from django.core.validators import MaxLengthValidator
from simple_history.models import HistoricalRecords
from simple_history import register
register(User, inherit=True)
class Company(models.Model):
"""
Model representing a company invested in.
"""
name = models.CharField(max_length=200)
#details
group=models.CharField(max_length=15, default='EQD')
stake = models.CharField(max_length=50, blank=True)
partners = models.CharField(max_length=50, blank=True)
#user details
modified_by = models.ForeignKey(User,related_name='Project_modified_by')
modified_date = models.DateTimeField(auto_now=True)
#to keep records
history = HistoricalRecords(inherit=True)
def __str__(self):
"""
String for representing the Model object.
"""
return self.name
def get_form_url(self):
"""
Returns the url to access the form to change model attributes.
"""
return reverse('forms', args=[str(self.id)])
def attrsetter(self,attr,value):
"""
set attribute of an instance
"""
return setattr(self, attr, value)
@property
def _history_user(self): #to track who modified
return self.modified_by
@_history_user.setter #to track what was modified
def _history_user(self, value):
self.modified_by = value
rec = Company(name='ABC',modified_date=datetime.datetime.now().date())
rec.save()
答案 0 :(得分:0)
所以我设法做到了。我必须创建一个名为" admin"的超级用户。第一
然后根据我的代码,modified_by字段不为null所以我需要给用户一个。以下作品
adminuser = User.objects.get(username='admin')
rec = Company(name='ABC',modified_date=datetime.datetime.now().date(),modified_by= adminuser)
rec.save()
但这会带来另一个问题,即每次运行代码时,它都会创建另一个实例。
createsuperuser
makemigrations
迁移
的runserver ..
所以需要加入适当的if子句