Skip to content

Commit

Permalink
Improve serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
raphodn committed Nov 26, 2024
1 parent 1162339 commit 5ab9d8e
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
6 changes: 5 additions & 1 deletion open_prices/api/prices/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ class PriceCreateSerializer(serializers.ModelSerializer):

class Meta:
model = Price
fields = Price.CREATE_FIELDS # + ["type"]
fields = Price.CREATE_FIELDS

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["type"].required = False


class PriceUpdateSerializer(serializers.ModelSerializer):
Expand Down
21 changes: 21 additions & 0 deletions open_prices/api/prices/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,27 @@ def test_price_create_with_location_id(self):
)
self.assertEqual(response.status_code, 201)

def test_price_create_with_type(self):
data = self.data.copy()
# without type? see other tests
# correct type
response = self.client.post(
self.url,
{**data, "type": price_constants.TYPE_PRODUCT},
headers={"Authorization": f"Bearer {self.user_session.token}"},
content_type="application/json",
)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.data["type"], price_constants.TYPE_PRODUCT)
# wrong type
response = self.client.post(
self.url,
{**data, "type": price_constants.TYPE_CATEGORY},
headers={"Authorization": f"Bearer {self.user_session.token}"},
content_type="application/json",
)
self.assertEqual(response.status_code, 400)

def test_price_create_with_app_name(self):
for params, result in [
("?", "API"),
Expand Down
2 changes: 1 addition & 1 deletion open_prices/api/prices/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def create(self, request: Request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
# get type
type = (
type = serializer.validated_data.get("type") or (
price_constants.TYPE_PRODUCT
if serializer.validated_data.get("product_code")
else price_constants.TYPE_CATEGORY
Expand Down
1 change: 1 addition & 0 deletions open_prices/prices/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ class Price(models.Model):
"receipt_quantity",
]
CREATE_FIELDS = UPDATE_FIELDS + [
"type", # optional in the serializer
"product_code",
"product_name",
"category_tag",
Expand Down

0 comments on commit 5ab9d8e

Please sign in to comment.