我有以下要求使用Django Rest Framework。 我需要在模型3的Get请求中处理对Model 2的POST请求
我有两个型号,只保留了几列
models.py
class Customers(models.Model): #original customers data are stored here
customer_id = models.BigIntegerField(db_column='customer_id', primary_key=True)
customer_name = models.CharField(db_column='Customer_name', blank=True, null=True, max_length=50)
class Customers_In_Use(models.Model): #where we will track the locking of customers data once they get used
customer_id = models.OneToOneField(Customers_Master, to_field='customer_id', on_delete=models.DO_NOTHING, related_name='rel_customer')
comments = models.TextField(blank=True,null=True)
一个数据库视图。
Customers_View(models.Model):
customer_id = models.BigIntegerField()
customer_name = models.CharField()
in_use = models.CharField(blank=True)
class Meta:
managed = False
此视图在后端构建,如下所示
Select
C.customer_id,
C.customer_name,
CASE WHEN U.customer_id_id IS NULL THEN 'No' ELSE 'Yes' END AS In_Use,
from Customers C
left join
Customers_In_Use U
on C.customer_id=U.customer_id_id
在我的Django Rest Api上,我基于Customers_View(GET请求)公开数据
我有一个对Customers_In_Use的POST请求,它将以json格式接收customer_id和注释。
Example Data on Customers_View:
customer_id,Customer_name,in_use
123,John,No
456,Smith,No
789,John,No
987,Tom,Yes #Yes means this customer data is already in use
567,Tom,No
现在在api上,如果我运行此请求
127.0.0.1:8000/api/customers_view/?in_use=No&customer_name=Tom
我应该得到如下结果
{
customer_id:567,
customer_name=Tom,
in_use:No
}
由于我收到了customer_id 567,我需要向Customers_In_Use发送帖子请求
Typical post request format with below data to be passed
{
comment:'I will use this data',
customer_id:567
}
现在我的问题是,这可以一次完成吗?
在customers_view上调用GET请求的那一刻,我们应该向Customers_In_Use发送帖子请求
从安静的一面:
我已经写了一份简单的listview来自customer_view
class customers_views_List(generics.ListAPIView):
queryset = customers_view.objects.all()
serializer_class = customers_views_serializer
on customers_in_use我使用了viewset
class customers_In_Use_api(viewsets.ModelViewSet):
lookup_field = 'customer_id'
queryset = customers_in_use.objects.all()
serializer_class = customers_in_use_Serializer
答案 0 :(得分:0)
是的,你可以,
只需覆盖您的类customers_In_Use_api。
的create方法您还必须将注释,customer_name和in_use放在正文请求中(如果您正在使用jquery ajax,只需将它放在数据字段中)例如
您必须通过in_use和name字段获取Customers_View的ID。
之后只需保存新的Customer_In_Use
创建功能的一个例子:
def create(self, request):
in_use = request.data.get('in_use')
name = request.data.get('customer_name')
comment = request.data.get('comment')
customers_view = get_object_or_404(Customers_View, customer_name=name)
if customers_view.in_use != in_use:
return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
serializer_datas['customer_id'] = customers_view.id
serializer_datas['comment'] = comment
serializer = customers_in_use_Serializer(serializer_datas)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
不要忘记状态和get_object_or_404之类的所有导入,它应该可以正常工作。 此代码未经过测试,因此您可能需要纠正一些错误