3๐
โ
It will be like
try:
category = Category.objects.get(format=format, page=page, order=order)
except Category.DoesNotExist:
# either make it None or create new category, depends on your requirement
category = None
# or create new category
except Category.MultipleObjectsReturned:
category = category.first() # it depends on your requirement
item.category = category
๐คUmar Asghar
2๐
At least there is one error,you should use get
to get only one category as you itemโs category instead of use filter
to get queryset
.
class ItemSerializer(serializers.ModelSerializer):
category = CategorySerializer()
data = serializers.ListField()
class Meta:
model = Item
fields = ('username', 'title', 'category', 'data')
def create(self, validated_data):
category_dict = validated_data.pop('category')
item = Item.objects.create(**validated_data)
format = category_dict.format
page = category_dict.page
order = category_dict.order
try:
item.category = Category.objects.get(format=format, page=page, order=order)
except Category.DoesNotExist:
pass
except Category.MultipleObjectsReturned:
pass
return item
๐คYkh
- [Django]-Execute background process from django that can't be interrupted by the web server
- [Django]-Deploying django app with heroku โ gunicorn not installing
- [Django]-Django OAuth2 Error: invalid_client and client_id=None when client_id has been provided
- [Django]-How to unit test image upload in Django REST Framework
- [Django]-Django + celery โ why my periodic task in not running?
Source:stackexchange.com