如何忽略错误而不返回400错误请求?-Django Rest Framework

时间:2018-07-13 20:04:53

标签: python django rest api django-rest-framework

我有一个名为Cart的模型。购物车具有优惠券的外键。

当我发布以创建新的购物车时,它会运行一些验证以查找Coupon是否存在。如果不是,则返回错误400,表明该对象不存在。 我不希望出现400错误,我需要它来继续将Coupon返回为Null的过程。

serializers.py

df$date = as.Date(paste0(df$Year_Month, "_01"), format = "%Y_%m_%d")


ggplot(df,
    aes(x=date,
        y=`Duration Average`,
        group=Business,
        color=Business,
        size=`MMR Count`)) +
  geom_line(aes(group=Business),stat="identity", size=1, alpha=0.7) +
  geom_point(aes(colour=Business, alpha=0.7)) +
  facet_wrap(~ Business, ncol=2) +
  scale_y_log10( limits=c(.1,1000),breaks=c(1,10,100,1000)) +   
  scale_alpha_continuous(range = c(0.5,1), guide='none') + 
  geom_text(aes(label=`Duration Average`,vjust=-1),size=3) +
  geom_text(aes(label=`MMR Count`,vjust=2),size=3,color="brown")

views.py

class CartSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(format='hex', read_only=True)
    delivery = DeliverySerializer(required=False, write_only=True)
    customer = CustomerSerializer(required=False, write_only=True)
    coupon = CouponSerializer(
    required=False,
    )
    totals = serializers.SerializerMethodField()


class CouponSerializer(serializers.Serializer):
    code = serializers.SlugRelatedField(
        slug_field='code',
        required=False,
        source='coupon',
        queryset=Coupon.objects.only_valid(),
    )

    def to_representation(self, coupon):
        return {
            'code': coupon.code,
            'discount_amount': coupon.discount_amount,
            'discount_percentage': coupon.discount_percentage,
            'only_first_order': coupon.only_first_order,
        }

3 个答案:

答案 0 :(得分:0)

根据2,您需要在序列化程序的相关字段中设置#!/usr/bin/env python from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from initializer import Setup from elements import Element as element class exampleTest(Setup): def test_Header(self): for i, browser in enumerate(Setup().browsers_waiting): # this does not work driver = browser["driver"] self.test_result = None try: driver.get('https://www.somewebsite.com') driver.implicitly_wait(20) elem = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, element.searchTitle)) ) headerText = elem.text expectedHeaderText = 'Some Header' self.assertEqual(expectedHeaderText, headerText) self.test_result = 'pass' except AssertionError as e: print ("Something went wrong. Error is %s\n" % e) self.test_result = 'fail' raise if __name__ == '__main__': unittest.main()

allow_null=True

请注意,class CartSerializer(serializers.ModelSerializer): id = serializers.UUIDField(format='hex', read_only=True) delivery = DeliverySerializer(required=False, write_only=True) customer = CustomerSerializer(required=False, write_only=True) coupon = CouponSerializer( required=False, allow_null=True, ) totals = serializers.SerializerMethodField() 模型中还需要null=True

答案 1 :(得分:0)

您需要为模型添加blank = True,因为它是外键 优惠券= models.ForeignKey('carts.Coupon',related_name='carts',on_delete=models.SET_NULL, null=True, blank=True )

关于模型中null和blank的区别,这里很好post

答案 2 :(得分:0)

我解决了以下问题:

从SlugRelatedField覆盖to_internal_value方法,将DoesNotExist异常视为不会引发错误。

class CouponSlugRelatedField(serializers.SlugRelatedField):

    def to_internal_value(self, code):
        try:
            return Coupon.objects.only_valid().get(code=code)
        except Coupon.DoesNotExist:
            return Coupon.objects.none()


class CouponSerializer(serializers.Serializer):
    code = CouponSlugRelatedField(
        slug_field='code',
        required=False,
        source='coupon',
        allow_null=True,
        queryset=Coupon.objects.only_valid()
    )

    def to_representation(self, coupon):
        return {
            'code': coupon.code,
            'discount_amount': coupon.discount_amount,
            'discount_percentage': coupon.discount_percentage,
            'only_first_order': coupon.only_first_order,
        }