Skip to content

Commit

Permalink
fix bug creating food with create form
Browse files Browse the repository at this point in the history
  • Loading branch information
smilerz committed Jan 13, 2022
1 parent d36033a commit b3f05b0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
5 changes: 4 additions & 1 deletion cookbook/models.py
Expand Up @@ -77,7 +77,10 @@ def get_or_create(self, *args, **kwargs):
for field in many_to_many:
field_model = getattr(obj, field).model
for related_obj in many_to_many[field]:
getattr(obj, field).add(field_model.objects.get(**dict(related_obj)))
if isinstance(related_obj, User):
getattr(obj, field).add(field_model.objects.get(id=related_obj.id))
else:
getattr(obj, field).add(field_model.objects.get(**dict(related_obj)))
return obj, True
except IntegrityError as e:
if 'Key (path)' in e.args[0]:
Expand Down
11 changes: 8 additions & 3 deletions cookbook/serializer.py
Expand Up @@ -394,15 +394,20 @@ def create(self, validated_data):
validated_data['supermarket_category'], sc_created = SupermarketCategory.objects.get_or_create(
name=validated_data.pop('supermarket_category')['name'],
space=self.context['request'].space)
onhand = validated_data.get('food_onhand', None)
onhand = validated_data.pop('food_onhand', None)

# assuming if on hand for user also onhand for shopping_share users
if not onhand is None:
shared_users = [user := self.context['request'].user] + list(user.userpreference.shopping_share.all())
if self.instance:
onhand_users = self.instance.onhand_users.all()
else:
onhand_users = []
if onhand:
validated_data['onhand_users'] = list(self.instance.onhand_users.all()) + shared_users
validated_data['onhand_users'] = list(onhand_users) + shared_users
else:
validated_data['onhand_users'] = list(set(self.instance.onhand_users.all()) - set(shared_users))
validated_data['onhand_users'] = list(set(onhand_users) - set(shared_users))

obj, created = Food.objects.get_or_create(**validated_data)
return obj

Expand Down

0 comments on commit b3f05b0

Please sign in to comment.