在休息框架中发布特定租金的联系人

时间:2017-03-28 12:34:10

标签: python django django-rest-framework

我正在开发一个租赁应用程序,以便将练习纳入休息框架。有一个功能,买家可以通过点击租金上的联系按钮联系租户所有者,然后填写他/她的email_id等。我知道如果我想联系特定的租金,那么我必须做这样的事情

rent = Rental.objects.get(id=token)
contact.objects.create(rent=rent, email_id=email_id, buyer=request.user)

我在序列化器的休息框架创建函数和APIView的post函数中混淆。我可以用我的例子来启发我吗?

class Rental(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=300, blank=False, null=False)
    phone_number = models.PositiveIntegerField(null=False, blank=False)


class Contact(models.Model):
    buyer = models.ForeignKey(User)
    rental = models.ForeignKey(Rental, related_name="rent")
    email_id = models.EmailField(blank=False, null=False)

class RentalSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source='user.username')
    galleries = GallerySerializer(many=True)
    class Meta:
        model = Rental
        fields = ('__all__')

class ContactSerializer(serializers.ModelSerializer):
    # buyer = UserSerializer(many=True)
    # rent = RentalSerializer(many=True)
    class Meta:
        model = Contact
        fields = '__all__'

class ContactedRent(APIView):
    serializer_class = ContactSerializer
    def get(self, request, token=None, format=None):
        """
        Returns a list of contactedRent
        """
        reply = {}
        try:
            contacted_rent = Contact.objects.filter(buyer_id=request.user.id)
            if token:
                specific_contacted_rent = contacted_rent.get(rental__id=token)
                reply['data'] = self.serializer_class(specific_contacted_rent).data
            else:
                print ('no token')
                reply['data'] = self.serializer_class(contacted_rent, many=True).data
        except Contact.DoesNotExist:
            return error.RequestedResourceNotFound().as_response()
        except:
            return error.UnknownError().as_response()
        else:
            return Response(reply, status.HTTP_200_OK)

    def post(self, request, token=None, format=None):
        """
        create a new contact to the rent
        """
        rent = None
        if not token is None:
            try:
                # contact = Contact.objects.get(buyer_id=request.user.id, rental__id=token)
                rent = Rental.objects.get(id=token)
            except Rental.DoesNotExist:
                return RequestedResourceNotFound().as_response()
            except:
                return UnknownError.as_response()
        serialized_data = self.serializer_class(instance=rent, data=request.data, partial=True)
        if serialized_data.is_valid():
            serialized_data.save()
        else:
            return error.ValidationError(serialized_data.errors).as_response() 

请有人帮我理解APIView的创建和发布功能。

更新

url(r'^contact/(?P<token>[0-9a-z]+)/$', ContactedRent.as_view(), name="create-contact-to-rent"),

此处令牌是通过提供买家信息(email_id)来联系的租金的ID

1 个答案:

答案 0 :(得分:1)

由于您不希望rental作为提交的数据传递,因此您可能希望将其从序列化程序中删除。

class ContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = Contact
        fields = ['buyer', 'email_id']  # omit `rental` field

序列化程序的partial参数用于PATCH个请求,当您只想验证提交的字段时,仅更新这些字段。 (我觉得您正在传递partial=True作为解决方法,因为序列化程序无法验证您是否未通过rental。)

从序列化程序中删除rental后,您现在应该可以执行以下操作:

serialized_data = self.serializer_class(data=request.data)

应该验证,因为您传递了有效的buyeremail_id值。然后,当您致电save时,您会传递rental实例

serialized_data.save(rental=rent)