我正在尝试使用Django Rest Framework创建后端,并试图确定业务逻辑应放在哪里。它会放在views.py中吗?我想创建比仅获取对象列表或抓取一个特定对象更复杂的服务。任何指导将不胜感激,谢谢。我知道有关通用Django项目中业务逻辑的讨论,但我特别询问django rest框架。
我正在尝试使用Django Rest Framework创建后端,并试图确定业务逻辑应放在哪里。它会放在views.py中吗?我想创建比仅获取对象列表或抓取一个特定对象更复杂的服务。任何指导将不胜感激,谢谢。我知道有关通用Django项目中业务逻辑的讨论,但我特别询问django rest框架。
这更多是关于设计模式而不是Django Rest Framework。
以下是一些提示:
假设您有一个在线咖啡店,您想为订购咖啡提供REST API。
以下是我建议的代码示例:
myapp/views.py:
def order(request, quantity=1):
# Process the order by calling the mapped method
order_id = CoffeeShopService.place_order(quantity)
return HttpResponse({'order_id': order_id, mimetype='application/json')
我的应用程序/services.py:
class CoffeeShopService(object):
@staticmethod
def place_order(quantity):
# do the business logic here
return order_id
Customer_Name is ""
这是明显的错误,通常代码存在问题。你应该使用验证框架(例如Marshmallow)。 - warvariucclass OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = (
'id',
'total',
'discount',
)
def calculate_discount(self, whatever_params):
# calculate discount if you need... and return it
def calculate_tax(self, whatever_params):
# calculate tax amount if you need...and return it
def calculate_grand_total(self, whatever_params):
# calculate grand total if you need and return it
def create(self, validated_data):
# You can make an order by applying
# some logic in the calculation method.
# Maybe by adding a bit of the context
# you sent as parameters from view.
django
项目架构的角度来看,这是不正确的。 - catscoolzhyk