Py学习  »  Django

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

Jay Desai • 6 年前 • 1842 次点击  

请看下面的代码:

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54299
文章 [ 1 ]  |  最新文章 6 年前