如何在Django Rest Framework中创建触发器以更改booleanfield?

时间:2018-09-21 07:49:41

标签: django django-models django-rest-framework

我在Django rest框架中有一个问题。由于我正在学习如何使用一些高级选项,因此我不太了解。每次将外键插入表中时,我目前都需要更改一个布尔字段。 我该如何在模型中做到这一点?

型号:

class Persona(models.Model):
    name = models.CharField(max_length=32)
    cart = models.ForeignKey(Credit,null=True)
    rg = models.IntergerField()
    end = models.CharField(max_length=256)
    details = models.TextField(blank=True, null=True)
    order = models.ForeignKey(Order, null=True)

    def __str__(self):
        return self.cart

    class Meta:
        db_table='person'
        app_label = 'bank'


class Credit(models.Model):
    number = models.CharField(max_length=16, unique=True)
    create_at = models.DateField(auto_add_now=True)
    updated_at = models.DateField()
    available = models.BooleanField()

    def __str__(self):
        return self.number

    class Meta:
        db_table = 'credit'
        app_label = 'bank'

序列化器:

class PersonaSerializer(serializers.ModelSerializer):
    order__id = serializers.ReadOnlyField(source='order.id')


    class Meta:
        model = Persona
        fields = '__all__'


class Persona(viewsets.ModelViewSet):

    allowed_methods = ('GET', 'POST', 'PUT', 'PATCH')
    queryset = Persona.objects.all()
    serializer_class = PersonaSerializer

1 个答案:

答案 0 :(得分:1)

您可以在create上覆盖ModelSerializer方法以实现此目的:

def create(self, validated_data):
    cart = validated_data['cart']
    persona = super(PersonaSerializer, self).create(validated_data)
    cart.available = True # update boolean
    cart.save()
    return persona

您可以在docs

中了解更多信息

如果要在模型中处理此问题,可以覆盖Persona模型save方法:

class Persona(models.Model):
    name = models.CharField(max_length=32)
    cart = models.ForeignKey(Credit,null=True)
    rg = models.IntergerField()
    end = models.CharField(max_length=256)
    details = models.TextField(blank=True, null=True)
    order = models.ForeignKey(Order, null=True)

    def __str__(self):
        return self.cart

    class Meta:
        db_table='person'
        app_label = 'bank'

    def save(self, *args, **kwargs):
        # Will only update the available field when the Persona
        # instance is created and the cart field is not null
        if not self.pk and self.cart:
            self.cart.available = True
            self.cart.save()
        return super(Persona, self).save(*args, **kwargs)