Coder Social home page Coder Social logo

Comments (9)

ruscoder avatar ruscoder commented on September 16, 2024 2

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 the categoryArray declaration: categoryArray = categoryArray(many=True, source='category')
  • Add related_name='details' to response_log = models.ForeignKey(response_log) (The drf-writable-nested current doesn't support implicit related_names, alas)
  • Add source='details' to the getCategoriesResponse 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.

ruscoder avatar ruscoder commented on September 16, 2024 1

I've created a separated issue to improve error messages. It's very easy to make a mistake like this.

from drf-writable-nested.

beautifulDrifter avatar beautifulDrifter commented on September 16, 2024

Thanks for the quick turn around! I was literally about to send you where I thought I saw the hiccup.

image

from drf-writable-nested.

ruscoder avatar ruscoder commented on September 16, 2024

@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.

beautifulDrifter avatar beautifulDrifter commented on September 16, 2024

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.

ruscoder avatar ruscoder commented on September 16, 2024

@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.

beautifulDrifter avatar beautifulDrifter commented on September 16, 2024

@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 serializer modex_connect.serializers.getCategoriesResponse, or set read_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.

ruscoder avatar ruscoder commented on September 16, 2024

@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.

beautifulDrifter avatar beautifulDrifter commented on September 16, 2024

from drf-writable-nested.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.