简体   繁体   English

在 postgresql 表 django 中插入数据

[英]Insert data in postgresql table django

Here is how my views.py looks like这是我的views.py的样子

@api_view(['GET', 'POST'])

def AnswersList(request):


if request.method == 'GET': # user requesting data 
    snippets = PAResponse.objects.all()
    serializer = PAAnswersSerializer(snippets, many=True)
    return Response(serializer.data)

elif request.method == 'POST': # user posting data
    serializer = PAAnswersSerializer(data=request.data)
    #print("serializer in post",type(serializer),serializer)
    if serializer.is_valid():
        serializer.save() # save to db
        result=Calculate(serializer)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

in post method i am sending my serializer as an argument to the "Calculate" function which is written in calculations.py.在 post 方法中,我将我的序列化程序作为参数发送到“计算”function,它是写在计算.py 中的。 Calculate function returns me a list.计算 function 给我一个列表。 but i am struggling on how can i send the element of list in different model from calculations.py list looks like this但是我正在努力解决如何从calculation.py列表中发送不同model中的列表元素看起来像这样
Result_list= [1,20,14,14,38,8,82] which i want to send in AnalysisResult class of model. Result_list= [1,20,14,14,38,8,82]我想在 model 的 AnalysisResult class 中发送。

My models.py我的模型.py

class AnalysisResult(models.Model):
user_id=models.IntegerField(primary_key=True)
E=models.IntegerField()
A=models.IntegerField()
C=models.IntegerField()
N=models.IntegerField()
O=models.IntegerField()
total=models.IntegerField()
class Meta:
    db_table='analysis_result'
    
def __str__(self):
    return self.response

Please let me know if you need any more information.如果您需要更多信息,请告诉我。 i am new to this so please help me.我是新手,所以请帮助我。

In simple terms can i send "Result_list" to db_table='analysis_result' directly from calculations.py instead of views or models.py if not then how can i send data.简单来说,我可以直接从calculation.py而不是views或models.py将“Result_list”发送到db_table='analysis_result' ,如果不是,那么我该如何发送数据。 Any kind of lead will be helpful任何类型的铅都会有帮助

DB=postgressql 13数据库=postgressql 13

I tried this in calculations.py我在calculation.py中试过这个

def Calculate(*args)
    ""some calucaltion""
    Result_lst.append(Total)
print("Result_lst",Result_lst)
for key,value in Ansdict.items():
    if key == 2:
        print("Question number",key)
        cursor = connections['postgres'].cursor()
        for d in Result_lst:
            cursor.execute("INSERT INTO analysis_result(user_id,E,A,C,N,O,total) VALUES (%s,%s,%s,%s,%s,%s,%s)",d)


return Result_lst   

 

I think the easiest way is to save the data via serializer.我认为最简单的方法是通过序列化程序保存数据。

In your case在你的情况下

...

if serializer.is_valid():
    serializer.save() # save to db
    result_list = Calculate(serializer) # result_list = [1, 20, 14, 14, 38, 8, 82]

    analysis_serializer = AnalysisResultSerializer(data={
       'user_id': result_list[0],
       'E': result_list[1],
       'A': result_list[2],
       'C': result_list[3],
       'N': result_list[4],
       'O': result_list[5],
       'total': result_list[6],
    })
    analysis_serializer.is_valid()
    analysis_serializer.save()

    return Response(serializer.data, status=status.HTTP_201_CREATED)
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM