Comments (9)
Hello @beautifulDrifter!
Thank you for finding the bug with different field names specified via source
attribute.
You have to fix the following errors:
- Update drf-writable-nested to 0.3.1 (just uploaded to PyPI)
- Add
source='category'
to thecategoryArray
declaration:categoryArray = categoryArray(many=True, source='category')
- Add
related_name='details'
toresponse_log = models.ForeignKey(response_log)
(The drf-writable-nested current doesn't support implicit related_names, alas) - Add
source='details'
to thegetCategoriesResponse
declaration:getCategoriesResponse = getCategoriesResponse(source='details')
- Pass list of
getCategoriesResponse
instead of one (because you have reverse FK field)
response = {'ack': 'Success',
'getCategoriesResponse': [{'categoryArray': [{'categoryBriefName': 'Collectibles',
'categoryId': 1,
'categoryLevel': 1,
'categoryName': 'Collectibles',
'leafCategory': 'false',
'traitCount': 1},
{'categoryBriefName': 'Everything Else',
'categoryId': 99,
'categoryLevel': 1,
'categoryName': 'Everything Else',
'leafCategory': 'false',
'traitCount': 5}]}],
'timestamp': '2017-10-12T12:00:40.000Z',
'version': '1.0'}
from drf-writable-nested.
I've created a separated issue to improve error messages. It's very easy to make a mistake like this.
from drf-writable-nested.
Thanks for the quick turn around! I was literally about to send you where I thought I saw the hiccup.
from drf-writable-nested.
@beautifulDrifter
Also you can use
getCategoriesResponse = getCategoriesResponse(source='response_log_detail', many=True)
without changing the default related_name
for the response_log
field
from drf-writable-nested.
Hey @ruscoder , now I am getting the following error.
/usr/local/lib/python3.4/dist-packages/drf_writable_nested/mixins.py in save(self, **kwargs)
171 self.save_kwargs = defaultdict(dict, kwargs)
172
--> 173 return super(BaseNestedModelSerializer, self).save(**kwargs)
174
175 def get_save_kwargs(self, field_name):TypeError: super(type, obj): obj must be an instance or subtype of type
I actually popped out the inner serializer to make sure that wasn't what was causing the issue.
class responseSerializer(WritableNestedModelSerializer):
# Fields #
#getCategoriesResponse = getCategoriesResponse()
ack = s.CharField(source='status')
timestamp = s.DateTimeField()
class Meta:
model = response_log
fields = (
'pk',
'ack',
#'getCategoriesResponse',
'timestamp',
)
from drf-writable-nested.
@beautifulDrifter I can't reproduce your problem
There is a working example:
class category(models.Model):
name = models.CharField(max_length=255, help_text="", blank=True)
short_name = models.CharField(max_length=255, help_text="", blank=True)
external_id = models.CharField(max_length=255, help_text="", blank=True)
def __str__(self):
return self.name
class response_log(models.Model):
timestamp = models.DateTimeField()
status = models.CharField(max_length=25)
class response_log_detail(models.Model):
response_log = models.ForeignKey(response_log)
category = models.ManyToManyField(category)
from rest_framework import serializers as s
from drf_writable_nested import WritableNestedModelSerializer
class categoryArray(s.ModelSerializer):
# Fields #
categoryId = s.IntegerField(source='external_id')
categoryName = s.CharField(source='name')
categoryBriefName = s.CharField(source='short_name')
class Meta:
model = category
fields = (
'categoryId',
'categoryName',
'categoryBriefName',
)
class getCategoriesResponse(WritableNestedModelSerializer):
# Fields #
categoryArray = categoryArray(many=True, source='category')
# errorMessage = bonanzaErrorMessage()
# warnings = bonanzaWarnings()
class Meta:
model = response_log_detail
fields = (
'pk',
'categoryArray',
# 'errorMessage',
# 'warnings',
)
class responseSerializer(WritableNestedModelSerializer):
# Fields #
getCategoriesResponse = getCategoriesResponse(source='response_log_detail', many=True)
ack = s.CharField(source='status')
class Meta:
model = response_log
fields = (
'pk',
'ack',
'getCategoriesResponse',
'timestamp',
)
response = {'ack': 'Success',
'getCategoriesResponse': [{
'categoryArray': [{'categoryBriefName': 'Collectibles',
'categoryId': 1,
'categoryLevel': 1,
'categoryName': 'Collectibles',
'leafCategory': 'false',
'traitCount': 1},
{
'categoryBriefName':
'Everything Else',
'categoryId': 99,
'categoryLevel': 1,
'categoryName': 'Everything Else',
'leafCategory': 'false',
'traitCount': 5}]}],
'timestamp': '2017-10-12T12:00:40.000Z',
'version': '1.0'}
serializer = serializers.responseSerializer(data=response)
serializer.is_valid(raise_exception=True)
response_log = serializer.save()
Note: make sure that you use drf-writable-nested 0.3.1
from drf-writable-nested.
@ruscoder unfortunately I cannot reformat the json, so I am making my models fit to it for now. I imagine that will be a typical use case as this will enable people to deserialize responses from external web services. Now I am getting the error but on the second (inner) serializer.
AssertionError: The
.create()
method does not support writable nested fields by default.
Write an explicit.create()
method for serializermodex_connect.serializers.getCategoriesResponse
, or setread_only=True
on nested serializer fields.
I have tried both setting a OneToOne on response_log_detail and a ForeignKey on response_log and neither have worked. Eventually I will flatten these two models once I get the deserialization working. I also removed the categoryArray from the getCategoriesResponse to validate that the responseSerializer worked properly and everything worked correctly. The fix you added only seems to be taking effect on the top level serializer OR it has something to do with the many to many. Let me know and thanks for all of your help!
Models:
class category(models.Model):
name = models.CharField(max_length=255, help_text="", blank=True)
short_name = models.CharField(max_length=255, help_text="", blank=True)
external_id = models.CharField(max_length=255, help_text="", blank=True)
def __str__(self):
return self.name
class response_log_detail(models.Model):
category_id = models.ManyToManyField(category)
#response_log = models.OneToOneField(response_log, null = True, blank = True)
class response_log(models.Model):
timestamp = models.DateTimeField()
status = models.CharField(max_length = 25, null=True, blank=True)
category_id = models.ManyToManyField(category)
response_log_detail = models.ForeignKey(response_log_detail, null=True, blank=True)
Serializers:
class categoryArray(s.ModelSerializer):
# Fields #
categoryId = s.IntegerField(source='external_id')
categoryName = s.CharField(source='name')
categoryBriefName = s.CharField(source='short_name')
class Meta:
model = category
fields = (
'categoryId',
'categoryName',
'categoryBriefName',
)
class getCategoriesResponse(WritableNestedModelSerializer):
# Fields #
categoryArray = categoryArray(many=True,source='category')
# errorMessage = bonanzaErrorMessage()
# warnings = bonanzaWarnings()
class Meta:
model = response_log_detail
fields = (
'pk',
'categoryArray',
# 'errorMessage',
# 'warnings',
)
class responseSerializer(WritableNestedModelSerializer):
# Fields #
getCategoriesResponse = getCategoriesResponse(source='response_log_detail')
ack = s.CharField(source='status')
timestamp = s.DateTimeField()
#getCategoriesResponse = getCategoriesResponse()
class Meta:
model = response_log
fields = (
'pk',
'getCategoriesResponse',
'ack',
'timestamp',
#'categoryArray',
)
from drf-writable-nested.
@beautifulDrifter
You have a mistake:
class getCategoriesResponse(WritableNestedModelSerializer):
# Fields #
categoryArray = categoryArray(many=True,source='category')
# errorMessage = bonanzaErrorMessage()
# warnings = bonanzaWarnings()
class Meta:
model = response_log_detail
fields = (
'pk',
'categoryArray',
# 'errorMessage',
# 'warnings',
)
in the line categoryArray = categoryArray(many=True,source='category')
.
It should be: categoryArray = categoryArray(many=True,source='category_id')
because you've renamed category
to category_id
.
from drf-writable-nested.
from drf-writable-nested.
Related Issues (20)
- "depth" property does not work? HOT 1
- You cannot call `.save()` after accessing `serializer.data`.If you need to access data before committing to the database then inspect 'serializer.validated_data' instead. HOT 2
- UniqueFieldMixin does not work for djangorestframwork of versions >= 3.11 HOT 1
- ValueError when trying to set a related id field to the wrong value HOT 1
- Parent instance is inaccesible in child validate data for reverse HOT 1
- Update nested related OneToOneField without providing its pk
- Delete reverse relations before update or create in NestedUpdateMixin HOT 4
- Migrate to new CI platform HOT 1
- Take into account the unique_together Models Meta field in UniqueFieldsMixin HOT 1
- The `.create()` method does not support writable nested fields by default
- Validation of child runs twice. Is this deliberate as it seems a bit inefficient to run the same code twice. HOT 5
- Error when trying to update reverse many-to-many relation
- Creating multiple objects with drf-writable-nested WritableNestedModelSerializer not creating the nested relation objects HOT 2
- how to use with self related field(manytomany)
- [Security] Changing related objects HOT 3
- Setting null when sending data as form data in one-to-one relationships
- The `.create()` method does not support writable nested fields by default. HOT 1
- Problem of pass through values to nested serializers from the call to the base serializer's save method. HOT 3
- Reverse Foreign Key is not working HOT 1
- Reverse FK relation got: TypeError: Car() got an unexpected keyword argument 'car_users'
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from drf-writable-nested.