/profile/User处的RelatedObjectDoesNotExist没有客户



我已经创建了用户Customer模型。我将模型迁移到与数据库同步的位置。然而,我得到了一个错误的用户没有客户。单击可通过配置文件页面http://127.0.0.1:8000/profile但在为每个用户添加配置文件代码后,我得到了以下错误

这是我的代码

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

# Create your models here.

class Customer(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
full_name = models.CharField(max_length=200, null=True)
address = models.CharField(max_length=100, null=True, blank=True)


def __str__(self):
return self.full_name


class  CustomerProfileView(TemplateView):
template_name = "app/CustomerProfile.html"


def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
customer = self.request.user.customer
context['customer'] = customer
orders = Order.objects.filter(cart__customer=customer).order_by("-id")
context["orders"] = orders
return context

正如错误所说,您使用了一个没有相关Customer对象的User对象。

因此,您必须为所有没有Customer的用户构造一个Customer记录。例如,您可以在数据迁移[Django-doc]中使用执行此操作

python manage.pymakemigrations --emptyapp_name

在数据迁移中,您可以为每个用户创建一个Customer,而不需要Customer:

from django.db import migrations
def create_customers(apps, schema_editor):
Customer = apps.get_model('app_name', 'Customer')
User = apps.get_model('auth', 'User')
customers = [
Customer(user=user, full_name=None, address=None)
for user in User.objects.filter(customer=None)
]
Customer.objects.bulk_create(customers)
class Migration(migrations.Migration):
dependencies = [
('app_name', '1234_some_migration'),
]
operations = [
migrations.RunPython(create_customers),
]

然后运行迁移,为所有现有用户构建客户。

相关内容

最新更新