需要在Django中对可写的嵌套序列化执行更新方法
model.py
class Product(models.Model):
product_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True)
product_name = models.CharField(unique=True,max_length=255)
class Client(models.Model):
client_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True)
org = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name='org',null=True)
product = models.ManyToManyField(Product,related_name='product')
client_name = models.CharField(unique=True,max_length=100)
....
serializers.py
class Clientpost_Serializers(serializers.ModelSerializer):
billing_method = Billingmethod_Serializers()
product = Product_Serializers(many=True)
def create(self, validated_data):
billing_method_data = validated_data.pop('billing_method')
product_data = validated_data.pop('product')
billing_method = Billing_Method.objects.create(**billing_method_data)
validated_data['billing_method'] = billing_method
client = Client.objects.create(**validated_data)
product = [Product.objects.create(**product_data) for product_data in product_data]
client.product.set(product)
return client
def update(self, instance, validated_data):
billing_method_data = validated_data.pop('billing_method')
billing_method = instance.billing_method
# product_data = validated_data.pop('product')
# product = instance.product
instance.currency = validated_data.get('currency', instance.currency)
instance.currency_type = validated_data.get('currency_type', instance.currency_type)
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.description = validated_data.get('description', instance.description)
instance.street_address = validated_data.get('street_address', instance.street_address)
instance.city = validated_data.get('city', instance.city)
instance.state = validated_data.get('state', instance.state)
instance.country = validated_data.get('country', instance.country)
instance.pincode = validated_data.get('pincode', instance.pincode)
instance.industry = validated_data.get('industry', instance.industry)
instance.company_size = validated_data.get('company_size', instance.company_size)
instance.client_name = validated_data.get('client_name', instance.client_name)
instance.contact_no = validated_data.get('contact_no', instance.contact_no)
instance.mobile_no = validated_data.get('mobile_no', instance.mobile_no)
instance.email_id = validated_data.get('email_id', instance.email_id)
instance.client_logo = validated_data.get('client_logo', instance.client_logo)
instance.client_code = validated_data.get('client_code', instance.client_code)
instance.save()
billing_method.billing_name = billing_method_data.get('billing_name', billing_method.billing_name)
billing_method.description = billing_method_data.get('description', billing_method.description)
billing_method.save()
# product.product_name = product_data.get('product_name', product.product_name)
# product.save()
product_data = validated_data.pop('product', [])
instance = super().update(instance, validated_data)
for products_data in product_data:
product = Product.objects.get(pk=products_data.get('product_id'))
product.product_name = products_data.get('product_name', product.product_name)
instance.product_data.add(product)
instance.save()
return instance
当我尝试在客户端端点执行put请求时,计费方法值正在更新,但产品值未更新。由于产品字段是很多到许多字段,这就是为什么我给出了很多= true并且无法在嵌套序列化器上执行更新的原因。
请帮助解决这个问题,因为我在这里呆了很长时间无法弄清楚这个问题。执行put时抛出错误的错误为
DoesNotExist at /api/onboarding/client/02de2d7e-2345-4727-bfa5-5ea5ffa22c63/
Product matching query does not exist.
Request Method: PUT
Request URL: http://127.0.0.1:8000/api/onboarding/client/02de2d7e-2345-4727-bfa5-5ea5ffa22c63/
Django Version: 3.2.12
Exception Type: DoesNotExist
Exception Value:
Product matching query does not exist.
Exception Location: C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py, line 435, in get
Python Executable: C:\Users\gobs4\AppData\Local\Programs\Python\Python310\python.exe
Python Version: 3.10.4
Python Path:
['F:\\PM-Onboarding-Service\\Onboarding-Service\\microservices',
'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip',
'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\DLLs',
'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\lib',
'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310',
'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages']
Server time: Wed, 18 May 2022 17:37:48 +0530
Traceback Switch to copy-and-paste view
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = await sync_to_async(response_for_exception, thread_sensitive=False)(request, exc)
return response
return inner
else:
@wraps(get_response)
def inner(request):
try:
response = get_response(request) …
except Exception as exc:
response = response_for_exception(request, exc)
return response
return inner
▶ Local vars
Variable Value
exc
DoesNotExist('Product matching query does not exist.')
get_response
<bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x000001D99899B190>>
request
<WSGIRequest: PUT '/api/onboarding/client/02de2d7e-2345-4727-bfa5-5ea5ffa22c63/'>
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response
if response is None:
wrapped_callback = self.make_view_atomic(callback)
# If it is an asynchronous view, run it in a subthread.
if asyncio.iscoroutinefunction(wrapped_callback):
wrapped_callback = async_to_sync(wrapped_callback)
try:
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
except Exception as e:
response = self.process_exception_by_middleware(e, request)
if response is None:
raise
# Complain if the view returned None (a common error).
▶ Local vars
Variable Value
callback
<function ClientDetail at 0x000001D99ACE7370>
callback_args
()
callback_kwargs
{'pk': UUID('02de2d7e-2345-4727-bfa5-5ea5ffa22c63')}
middleware_method
<bound method CsrfViewMiddleware.process_view of <django.middleware.csrf.CsrfViewMiddleware object at 0x000001D99899B640>>
request
<WSGIRequest: PUT '/api/onboarding/client/02de2d7e-2345-4727-bfa5-5ea5ffa22c63/'>
response
None
self
<django.core.handlers.wsgi.WSGIHandler object at 0x000001D99899B190>
wrapped_callback
<function ClientDetail at 0x000001D99ACE7370>
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py, line 54, in wrapped_view
def csrf_exempt(view_func):
"""Mark a view function as being exempt from the CSRF view protection."""
# view_func.csrf_exempt = True would also work, but decorators are nicer
# if they don't have side effects, so return a new function.
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs) …
wrapped_view.csrf_exempt = True
return wraps(view_func)(wrapped_view)
▶ Local vars
Variable Value
args
(<WSGIRequest: PUT '/api/onboarding/client/02de2d7e-2345-4727-bfa5-5ea5ffa22c63/'>,)
kwargs
{'pk': UUID('02de2d7e-2345-4727-bfa5-5ea5ffa22c63')}
view_func
<function ClientDetail at 0x000001D99ACE72E0>
models.py
class Product(models.Model):
product_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True)
product_name = models.CharField(unique=True,max_length=255)
class Client(models.Model):
client_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True)
org = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name='org',null=True)
product = models.ManyToManyField(Product,related_name='product')
client_name = models.CharField(unique=True,max_length=100)
....
serializers.py
class Clientpost_Serializers(serializers.ModelSerializer):
billing_method = Billingmethod_Serializers()
product = Product_Serializers(many=True)
def create(self, validated_data):
billing_method_data = validated_data.pop('billing_method')
product_data = validated_data.pop('product')
billing_method = Billing_Method.objects.create(**billing_method_data)
validated_data['billing_method'] = billing_method
client = Client.objects.create(**validated_data)
product = [Product.objects.create(**product_data) for product_data in product_data]
client.product.set(product)
return client
def update(self, instance, validated_data):
billing_method_data = validated_data.pop('billing_method')
billing_method = instance.billing_method
# product_data = validated_data.pop('product')
# product = instance.product
instance.currency = validated_data.get('currency', instance.currency)
instance.currency_type = validated_data.get('currency_type', instance.currency_type)
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.description = validated_data.get('description', instance.description)
instance.street_address = validated_data.get('street_address', instance.street_address)
instance.city = validated_data.get('city', instance.city)
instance.state = validated_data.get('state', instance.state)
instance.country = validated_data.get('country', instance.country)
instance.pincode = validated_data.get('pincode', instance.pincode)
instance.industry = validated_data.get('industry', instance.industry)
instance.company_size = validated_data.get('company_size', instance.company_size)
instance.client_name = validated_data.get('client_name', instance.client_name)
instance.contact_no = validated_data.get('contact_no', instance.contact_no)
instance.mobile_no = validated_data.get('mobile_no', instance.mobile_no)
instance.email_id = validated_data.get('email_id', instance.email_id)
instance.client_logo = validated_data.get('client_logo', instance.client_logo)
instance.client_code = validated_data.get('client_code', instance.client_code)
instance.save()
billing_method.billing_name = billing_method_data.get('billing_name', billing_method.billing_name)
billing_method.description = billing_method_data.get('description', billing_method.description)
billing_method.save()
# product.product_name = product_data.get('product_name', product.product_name)
# product.save()
product_data = validated_data.pop('product', [])
instance = super().update(instance, validated_data)
for products_data in product_data:
product = Product.objects.get(pk=products_data.get('product_id'))
product.product_name = products_data.get('product_name', product.product_name)
instance.product_data.add(product)
instance.save()
return instance
When I tried to perform PUT request in Client Endpoint the billing method value is getting updated but the product value is not getting updated. As the product field is a many to many field and that's why I have given many = True and can't able to perform update on the nested serializer.
Kindly help to resolve this issue, as I was stuck here for so long can't able to figure out the problem. The error throwing while performing PUT is
DoesNotExist at /api/onboarding/client/02de2d7e-2345-4727-bfa5-5ea5ffa22c63/
Product matching query does not exist.
Request Method: PUT
Request URL: http://127.0.0.1:8000/api/onboarding/client/02de2d7e-2345-4727-bfa5-5ea5ffa22c63/
Django Version: 3.2.12
Exception Type: DoesNotExist
Exception Value:
Product matching query does not exist.
Exception Location: C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py, line 435, in get
Python Executable: C:\Users\gobs4\AppData\Local\Programs\Python\Python310\python.exe
Python Version: 3.10.4
Python Path:
['F:\\PM-Onboarding-Service\\Onboarding-Service\\microservices',
'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip',
'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\DLLs',
'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\lib',
'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310',
'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages']
Server time: Wed, 18 May 2022 17:37:48 +0530
Traceback Switch to copy-and-paste view
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = await sync_to_async(response_for_exception, thread_sensitive=False)(request, exc)
return response
return inner
else:
@wraps(get_response)
def inner(request):
try:
response = get_response(request) …
except Exception as exc:
response = response_for_exception(request, exc)
return response
return inner
▶ Local vars
Variable Value
exc
DoesNotExist('Product matching query does not exist.')
get_response
<bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x000001D99899B190>>
request
<WSGIRequest: PUT '/api/onboarding/client/02de2d7e-2345-4727-bfa5-5ea5ffa22c63/'>
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response
if response is None:
wrapped_callback = self.make_view_atomic(callback)
# If it is an asynchronous view, run it in a subthread.
if asyncio.iscoroutinefunction(wrapped_callback):
wrapped_callback = async_to_sync(wrapped_callback)
try:
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
except Exception as e:
response = self.process_exception_by_middleware(e, request)
if response is None:
raise
# Complain if the view returned None (a common error).
▶ Local vars
Variable Value
callback
<function ClientDetail at 0x000001D99ACE7370>
callback_args
()
callback_kwargs
{'pk': UUID('02de2d7e-2345-4727-bfa5-5ea5ffa22c63')}
middleware_method
<bound method CsrfViewMiddleware.process_view of <django.middleware.csrf.CsrfViewMiddleware object at 0x000001D99899B640>>
request
<WSGIRequest: PUT '/api/onboarding/client/02de2d7e-2345-4727-bfa5-5ea5ffa22c63/'>
response
None
self
<django.core.handlers.wsgi.WSGIHandler object at 0x000001D99899B190>
wrapped_callback
<function ClientDetail at 0x000001D99ACE7370>
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py, line 54, in wrapped_view
def csrf_exempt(view_func):
"""Mark a view function as being exempt from the CSRF view protection."""
# view_func.csrf_exempt = True would also work, but decorators are nicer
# if they don't have side effects, so return a new function.
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs) …
wrapped_view.csrf_exempt = True
return wraps(view_func)(wrapped_view)
▶ Local vars
Variable Value
args
(<WSGIRequest: PUT '/api/onboarding/client/02de2d7e-2345-4727-bfa5-5ea5ffa22c63/'>,)
kwargs
{'pk': UUID('02de2d7e-2345-4727-bfa5-5ea5ffa22c63')}
view_func
<function ClientDetail at 0x000001D99ACE72E0>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需要一个
You just need a