为了账号安全,请及时绑定邮箱和手机立即绑定

如何迭代 django 模型的查询列表

如何迭代 django 模型的查询列表

慕后森 2021-11-30 16:45:55
我正在从网站读取 json 文件,如果该记录不在我的客户查询集中,我想为该记录创建一个新客户。发生的事情是当我遍历查询集时,Django 试图创建一个新的 Customer,即使它已经在查询集中。请看我下面的代码:from rest_framework import genericsfrom customer.models import Customersfrom .serializers import CustomersSerializerimport jsonimport urllib.requestclass CustomerAPIView(generics.ListAPIView):    j = urllib.request.urlopen("https://web.njit.edu/~jsd38/json/customer.json")    customer_data = json.load(j)    queryset1 = Customers.objects.values_list('CustomerId', flat=True)    for customer in customer_data:        if customer["@Id"] not in queryset1.iterator():            CustomerId = customer["@Id"]            Name = customer["Name"]            PhoneNumber = customer["PhoneNumber"]            EmailAddress = customer["EmailAddress"]            StreetLine = customer["Address"]["StreetLine1"]            City = customer["Address"]["City"]            StateCode = customer["Address"]["StateCode"]            PostalCode = customer["Address"]["PostalCode"]            cus = Customers()            cus.CustomerId = CustomerId            cus.Name = Name            cus.PhoneNumber = PhoneNumber            cus.EmailAddress = EmailAddress            cus.StreetLine = StreetLine            cus.City = City            cus.StateCode = StateCode            cus.PostalCode = PostalCode            cus.save()    queryset = Customers.objects.all()    serializer_class = CustomersSerializer
查看完整描述

1 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

您的 JSON 正在返回“@Id”键的字符串,我假设您的模型Customers将整数作为CustomerId字段。

您应该将它们转换为stror int

if int(customer["@Id"]) not in queryset1:
    ...


查看完整回答
反对 回复 2021-11-30
  • 1 回答
  • 0 关注
  • 151 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信