简体   繁体   English

如何遍历Django模型的查询列表

[英]How to iterate over Query List of django model

I am reading a json file from a website and if the record is not in my Customers queryset I want to create a new Customer for that record. 我正在从网站上读取json文件,如果该记录不在我的客户查询集中,则我想为该记录创建一个新客户。 What is happening is when I iterate over the queryset, Django is trying to create a new Customer even when it is already in the queryset. 发生的事情是,当我遍历查询集时,Django试图创建一个新客户,即使该客户已在查询集中也是如此。

Please see my code below: 请在下面查看我的代码:

from rest_framework import generics
from customer.models import Customers
from .serializers import CustomersSerializer
import json
import urllib.request

class 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

Your JSON is returning strings for the "@Id" key, I'm assuming your model Customers has integers as CustomerId field. 您的JSON返回“ @Id”键的字符串,我假设您的模型“ Customers具有整数作为“ CustomerId ID”字段。

You should convert them to str or int : 您应该将它们转换为strint

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

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

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