[英]Django: null value in column “user_id” violates not-null constraint
I'm using Postgresql and I have created the following models in my Django Project.我正在使用 Postgresql 并在我的 Django 项目中创建了以下模型。
Models.py模型.py
User = settings.AUTH_USER_MODEL
Discount_Type=(
('$', '$'),
('%', '%'),
)
class Invoice(models.Model):
ticket = models.OneToOneField(Ticket, related_name='invoice', blank=True,null=True, on_delete=models.CASCADE)
updated_by = models.ForeignKey(User, null=True, blank=True, related_name='invoice_editor', on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
is_paid = models.BooleanField(default=False)
federal_price = models.DecimalField(default=20.00, max_digits=6, decimal_places=2)
federal_qty = models.PositiveIntegerField(default=1)
federal_amount = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2)
state_price = models.DecimalField(default=20.00, max_digits=6, decimal_places=2)
state_qty = models.PositiveIntegerField(default=1)
state_amount = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2)
total_amount = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2)
discount = models.DecimalField(default=0.00, max_digits=6, decimal_places=2)
discount_type = models.CharField(default='$', max_length=5, choices=Discount_Type)
discount_value = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2)
amount_payable = models.DecimalField(null=True, blank=True, max_digits=6, decimal_places=2)
def __str__(self):
return str(self.amount_payable)
class Meta:
ordering = ['-date_updated']
class Ticket(models.Model):
tax_year = models.CharField(max_length=50, default='2020')
service = models.CharField(max_length=50, default='Tax Filing')
description = models.TextField(max_length=1000, blank=True)
customer = models.ForeignKey(User, related_name='ticket_customer', on_delete=models.CASCADE)
agents = models.ManyToManyField(User, related_name="ticket_agents", blank=True)
support = models.ForeignKey(User, related_name='ticket_support', blank=True, null=True, on_delete=models.SET_NULL)
preparation = models.ForeignKey(User, related_name='ticket_preparation', blank=True, null=True, on_delete=models.SET_NULL)
filing = models.ForeignKey(User, related_name='ticket_filing', blank=True, null=True, on_delete=models.SET_NULL)
class Notification(models.Model):
ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, related_name="notification_ticket", blank=True, null=True)
sender = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="notification_from_user", blank=True, null=True)
receivers = models.ManyToManyField(User, related_name="notification_to_user", blank=True)
seen_by = models.ManyToManyField(User, related_name="notification_seen_by", blank=True)
text_preview = models.CharField(max_length=255, blank=True)
record_id = models.CharField(max_length=255, blank=True)
date = models.DateTimeField(auto_now_add=True)
class Meta:
ordering: ['-date']
def __str__(self):
return self.text_preview
My forms.py我的 forms.py
class TicketCreateForm(forms.ModelForm):
class Meta:
model = Ticket
fields = ('tax_year', 'service', 'description',)
widgets = {
'tax_year': forms.Select(attrs={'class': 'form-control'}),
'service': forms.Select(attrs={'class': 'form-control'}),
'description': forms.Textarea(attrs={'rows':3, 'cols':60, 'class':'form-control'}),
}
my views.py我的观点.py
def customer_ticket_create(request):
form = TicketCreateForm()
if request.method == 'POST':
form = TicketCreateForm(request.POST or None)
if form.is_valid():
ticket = form.save(commit=False)
ticket.customer = request.user
ticket.save()
Invoice.objects.create( ticket=ticket, updated_by=request.user)
return redirect('customer_home')
But I'm getting django.db.utils.IntegrityError: "user_id" violates not-null constraint.但我得到 django.db.utils.IntegrityError: "user_id" 违反非空约束。 This error is because of Invoice.objects.create(ticket=ticket, updated_by=request.user) Without this line, my view is working fine.
此错误是由于 Invoice.objects.create(ticket=ticket, updated_by=request.user) 没有此行,我的视图工作正常。 I'm getting the same error even when I tried to create the Invoice from SHELL.
即使我尝试从 SHELL 创建发票,我也会遇到同样的错误。
Not sure why the view is not able to create Invoice.不知道为什么视图无法创建发票。 Can someone please help me?
有人可以帮帮我吗?
So far I have tried the following solution from other similar questions: Updating the ForeignKey Model fields in Invoice Model with (null=True, Blank=True) Deleting the Migrations Files and Database.到目前为止,我已经尝试了其他类似问题的以下解决方案:更新 Invoice Model 中的 ForeignKey Model 字段,使用(null=True,Blank=True)删除迁移文件和数据库。 Running migrations and migrate and tried to create the Invoice again but still getting the same error.
运行迁移和迁移并尝试再次创建发票,但仍然出现相同的错误。
Error Traceback错误回溯
Environment:环境:
Request Method: POST
Request URL: http://127.0.0.1:8000/ticket/create
Django Version: 3.1.4
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.forms',
'accounts',
'customers',
'tickets',
'message',
'organizer',
'documents',
'agents',
'invoices',
'notifications',
'workflow',
'allauth',
'allauth.account',
'allauth.socialaccount',
'intl_tel_input',
'localflavor',
'django_filters',
'crispy_forms',
'storages',
'debug_toolbar',
'django_extensions']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.common.BrokenLinkEmailsMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'csp.middleware.CSPMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback (most recent call last):
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
The above exception (null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (38, 18, null).
) was the direct cause of the following exception:
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Sai Maruthi\Documents\Dev\lappy\src\accounts\decorators.py", line 20, in wrapper_func
return view_func(request, *args, **kwargs)
File "C:\Users\Sai Maruthi\Documents\Dev\lappy\src\tickets\views.py", line 61, in customer_ticket_create
Invoice.objects.create(
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\base.py", line 801, in save_base
post_save.send(
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\dispatch\dispatcher.py", line 177, in send
return [
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\dispatch\dispatcher.py", line 178, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\Sai Maruthi\Documents\Dev\lappy\src\invoices\signals.py", line 88, in invoice_update_notification
notification.seen_by.set([ticket.customer, ticket.support, ticket.preparation, ticket.filing, ticket.fbar, ticket.itin, ticket.extra])
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1015, in set
self.add(*new_objs, through_defaults=through_defaults)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\fields\related_descriptors.py", line 950, in add
self._add_items(
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1130, in _add_items
self.through._default_manager.using(db).bulk_create([
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\query.py", line 506, in bulk_create
returned_columns = self._batched_insert(
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\query.py", line 1277, in _batched_insert
self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 198, in execute
return self._record(self.cursor.execute, sql, params)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 133, in _record
return method(sql, params)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Sai Maruthi\.virtualenvs\lappy-FT-EdR8P\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
Exception Type: IntegrityError at /ticket/create
Exception Value: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (38, 18, null).
EDIT-1编辑-1
@receiver(post_save, sender=Invoice)
def invoice_update_notification(sender, instance, **kwargs):
if instance.is_paid:
ticket = instance.ticket
notification = Notification.objects.create(
ticket=ticket,
sender=instance.updated_by,
text_preview= f'Received Payment- {instance.amount_payable}',
record_id=instance.id,)
notification.seen_by.set([ticket.customer, ticket.support, ticket.preparation, ticket.filing])
else:
ticket = instance.ticket
notification = Notification.objects.create(
ticket=ticket,
sender=instance.updated_by,
text_preview= f'Invoice Updated - {instance.amount_payable}',
record_id=instance.id,)
notification.seen_by.set([ticket.customer, ticket.support, ticket.preparation, ticket.filing])
ticket.support
, ticket.preparation
and ticket.filing
are all nullable meaning that any of them could be None
. ticket.support
、 ticket.preparation
和ticket.filing
都是可以为空的,这意味着它们中的任何一个都可以是None
。 You need to filter out the fields that are null.您需要过滤掉 null 的字段。
The built-in function filter
can be used to filter out items from a list that are "falsy" like None
by passing None
as the first argument内置的 function
filter
可用于通过将None
作为第一个参数传递来过滤掉列表中“虚假”的项目,例如None
users = list(filter(None, [ticket.customer, ticket.support, ticket.preparation, ticket.filing]))
notification.seen_by.set(users)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.