[英]Django: Save auth_user to model with Foreign Key
The scenario is the following:场景如下:
I have a Django form which places a post request to the backend.我有一个 Django 表单,它向后端发出一个 post 请求。 With this data, I create an instance of my order model.
使用这些数据,我创建了一个订单模型的实例。 One order can have one customer and a customer can have one auth_user.
一个订单可以有一个客户,一个客户可以有一个 auth_user。 Database is SQLite.
数据库是 SQLite。 The relation looks like this:
关系如下所示:
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.RESTRICT)
class Customer(models.Model):
email = models.CharField(max_length=MAX_TEXT_LENGTH)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
I managed to save all of them, order and customer are correctly related in the database.我设法保存了所有这些,订单和客户在数据库中正确相关。 Although I am somehow failing while saving the user to customer.
尽管我在将用户保存给客户时以某种方式失败了。 I save them like this in my view.py:
我将它们保存在我的 view.py 中:
with transaction.atomic():
# create customer & order
customer = create_customer(first_name, last_name, email, phone)
order = create_order(customer, form.cleaned_data)
# add additional stuff to order
order.additional_services.add(*form.cleaned_data['additional_service']),
order.save
# create user and update customer
plain_user_password = generatePassword(DEFAULT_PASSWORD_LENGTH)
user = create_user(order.id, email, plain_user_password, first_name, last_name)
customer.user = user
customer.save
I create all my models with Model.objects.create(...)
我用
Model.objects.create(...)
创建了我所有的模型
Using the order.id as username is a given and cannot be changed.使用 order.id 作为用户名是给定的,不能更改。 The last two lines seem not to work, although the customer holds the correct user_id afterwards (verified by debugging), the column in the database table is null... No exception occurring when I use a try-catch block either...
最后两行似乎不起作用,尽管客户随后持有正确的 user_id(通过调试验证),但数据库表中的列为空......当我使用 try-catch 块时也没有发生异常......
What am I missing?我错过了什么? Any help much appreciated :)
非常感谢任何帮助:)
See: https://docs.djangoproject.com/en/3.1/ref/models/instances/#how-django-knows-to-update-vs-insert请参阅: https : //docs.djangoproject.com/en/3.1/ref/models/instances/#how-django-knows-to-update-vs-insert
solution: -> customer.save(force_update=True)解决方案:-> customer.save(force_update=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.