M
M
matveyvarg2016-07-28 15:56:54
Django
matveyvarg, 2016-07-28 15:56:54

Why does an AttributeError occur?

Mistake:

AttributeError at /orders/
'NoneType' object has no attribute 'add'

The code itself:
def create(self, validated_data):

        address_data = dict(validated_data.pop('address'))
        print address_data
        address = Address.objects.create(**address_data)

        instance = Order.objects.create(address=address, **validated_data)
        session_id = self.context['request'].session.session_key
        burger_ids = SessionOrder.objects.filter(session_id=session_id)
        for item in burger_ids:
            burger = Burger.objects.get(id=item.burger_id)
            instance.burgers.add(burger)

        return instance

Checked, instance is definitely not None.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-07-28
@matveyvarg

In addition to changing the burgers field type from ForeignKey to ManyToManyField, it's better to change the code like this

burger_ids = [i.burger_id for i in SessionOrder.objects.filter(session_id=session_id)]
burgers = Burger.objects.filter(id__in=burger_ids)
instance.burgers.add(*burgers)

This will reduce the number of requests from N*2 (where N is the number of instances of the Burger model) to two.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question