django-rest-framework - trying to set required=Fal

2019-07-27 11:21发布

I'm having some issue with django-rest-framework, and nested objects.

I have a Cart object, as well as CartItem, which links back to a Cart:

class Cart(models.Model):
    customer = models.ForeignKey(Customer)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

class CartItem(models.Model):
    cart = models.ForeignKey(Cart, related_name='cartitems')
    product = models.ForeignKey(Product, help_text='Product in a cart')
    quantity = models.PositiveIntegerField(default=1, help_text='Quantity of this product.')
    date_added = models.DateTimeField(auto_now_add=True, help_text='Date that this product was added to the cart.')

I've created serializers for both:

class CartItemSerializer(serializers.ModelSerializer):
    product = serializers.HyperlinkedRelatedField(view_name='product-detail')

    class Meta:
        model = CartItem

class CartSerializer(serializers.ModelSerializer):
    customer = serializers.HyperlinkedRelatedField(view_name='customer-detail')
    cartitems = CartItemSerializer(required=False)
    total_price = serializers.CharField(source='total_price', read_only=True)
    shipping_cost = serializers.CharField(source='shipping_cost', read_only=True)

    class Meta:
        model = Cart
        fields = ('id', 'customer', 'date_created', 'date_modified', 'cartitems', 'total_price', 'shipping_cost')

However, whenever I try to POST to create a new cart, I get an error, assumedly when it tries to set the non-existent CartItem:

TypeError at /api/v1/carts/
add() argument after * must be a sequence, not NoneType

However, a Cart isn't required to actually have CartItems.

Is there any way to get DRF to respect the required=False flag I get on Cart.cartitems?

Cheers, Victor

EDIT:

I took a stab at tracing it through again:

It's calling BaseSerializer.save() in rest_framework/serializers.py with a CartSerializer object.

def save(self, **kwargs):
    """
    Save the deserialized object and return it.
    """
    if isinstance(self.object, list):
        [self.save_object(item, **kwargs) for item in self.object]

        if self.object._deleted:
            [self.delete_object(item) for item in self.object._deleted]
    else:
        self.save_object(self.object, **kwargs)

    return self.object

It then calls save_object() on the same class:

def save_object(self, obj, **kwargs):
    """
    Save the deserialized object and return it.
    """
    if getattr(obj, '_nested_forward_relations', None):
        # Nested relationships need to be saved before we can save the
        # parent instance.
        for field_name, sub_object in obj._nested_forward_relations.items():
            if sub_object:
                self.save_object(sub_object)
            setattr(obj, field_name, sub_object)

    obj.save(**kwargs)

    if getattr(obj, '_m2m_data', None):
        for accessor_name, object_list in obj._m2m_data.items():
            setattr(obj, accessor_name, object_list)
        del(obj._m2m_data)

    if getattr(obj, '_related_data', None):
        for accessor_name, related in obj._related_data.items():
            if isinstance(related, RelationsList):
                # Nested reverse fk relationship
                for related_item in related:
                    fk_field = obj._meta.get_field_by_name(accessor_name)[0].field.name
                    setattr(related_item, fk_field, obj)
                    self.save_object(related_item)

                # Delete any removed objects
                if related._deleted:
                    [self.delete_object(item) for item in related._deleted]

            elif isinstance(related, models.Model):
                # Nested reverse one-one relationship
                fk_field = obj._meta.get_field_by_name(accessor_name)[0].field.name
                setattr(related, fk_field, obj)
                self.save_object(related)
            else:
                # Reverse FK or reverse one-one
                setattr(obj, accessor_name, related)
        del(obj._related_data)

The Cart object has a _related_data field that is set to a dict:

{'cartitems': None}

Hence, on the second-last line, it calls setattr in django/db/models/fields/related.py:

def __set__(self, instance, value):
    if instance is None:
        raise AttributeError("Manager must be accessed via instance")

    manager = self.__get__(instance)
    # If the foreign key can support nulls, then completely clear the related set.
    # Otherwise, just move the named objects into the set.
    if self.related.field.null:
        manager.clear()
    manager.add(*value)

It's this last liner (manager.add(*value)) that causes the:

TypeError: add() argument after * must be a sequence, not NoneType

1条回答
祖国的老花朵
2楼-- · 2019-07-27 11:42

Checking the Serializer Relation Docs, first you need to add many=True to your cartitems field.

Unfortunately this is read-only. The docs just say "For read-write relationships, you should use a flat relational style" — you can find a question about that here (although that's only dealing with the 1-1 case).

Current strategies involve making cartitems read-only and then either: doing something post_save, using a second serializer or making a separate request to a separate endpoint to set the related entities. Given that better support for Nested Writes is coming I'd probably be inclined towards a separate request to a separate endpoint for the moment (though that will obviously depend on your constraints).

I hope that helps.

EDIT: (After update to question & discussion in comments).

If you're using a separate endpoint for adding CartItems then making cartitems read-only should eliminate the error.

However (if you're not making it read-only) looking at the DRF code you posted from save_object it occurs that in the related_item in related block you really do need a list. The appropriate dict (fragment) for a Cart with no CartItems is not {'cartitems': None} but rather {'cartitems': []}. — This of course means your required=False flag isn't doing anything. (So perhaps the short answer is "No" — Will now defer to the mailing list discussion

查看更多
登录 后发表回答