dict包含不在字段名中的字段

时间:2018-02-25 02:07:32

标签: python django csv serializer

这是我创建查询集的csv文件的函数

  def esport_to_csv(self, tweets):
        with open('tweets.csv', 'w') as new_file:
            fieldnames = ["tweet_id", "text" , "user_screen_name", "user_name", "user_verified", "created_at", "user_time_zone", "user_location", "favorite_count", "retweet_count", "user_followers_count", "user_friends_count"]
            csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter='\t')
            csv_writer.writeheader()
            for tweet in tweets:
                line = []
                line.append(tweet["tweet_id"])
                line.append(tweet["text"])
                line.append(tweet["user_screen_name"])
                line.append(tweet["user_name"])
                line.append(tweet["user_verified"])
                line.append(tweet["created_at"])
                line.append(tweet["user_time_zone"])
                line.append(tweet["user_location"])
                line.append(tweet["favorite_count"])
                line.append(tweet["retweet_count"])
                line.append(tweet["user_followers_count"])
                line.append(tweet["user_friends_count"])
                csv_writer.writerow(line)

这是我的服务器响应

ValueError: dict contains fields not in fieldnames: 967563194582515712, 'RT @KEEMSTAR: When you have your fathers car & you tell everyone on the internet that your 15 year old ass bought it. t.co/bUhhrPw0…', 'TKBrotherTK', 'Team Kalvin', False, '2018-02-25T06:23:36+05:30', 'Melbourne', 'Australia', 0, 0, None, None

这是来自名为

的函数
@list_route(methods=["post"])
    def get_created_in_range(self, request):
        response = {}
        data = request.POST
        start = dateutil.parser.parse(data['start'])
        end = dateutil.parser.parse(data['end'])
        page_no = data['page_no']
        export_to_csv = data.get('export_to_csv', "false")
        tweets = Tweet.get_created_in_range(start, end, int(page_no))
        serializer = TweetSerializer(tweets, many= True)
        if export_to_csv == "true":
           self.esport_to_csv(serializer.data)
        print(type(serializer.data[0]))
        response["data"] = serializer.data
        return Response(response, status= status.HTTP_200_OK)

如果你能看到上面的函数调用,那么

如果export_to_csv ==“true”:        self.esport_to_csv(serializer.data)

我在网上看过一个解决方案,但我不知道如何在这里应用它

1 个答案:

答案 0 :(得分:2)

您需要将dict传递给DictWriter,并告诉它忽略额外字段(如果存在)。试试这个:

  def esport_to_csv(self, tweets):
    with open('tweets.csv', 'w') as new_file:
        fieldnames = ["tweet_id", "text" , "user_screen_name", "user_name", "user_verified", "created_at", "user_time_zone", "user_location", "favorite_count", "retweet_count", "user_followers_count", "user_friends_count"]
        csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter='\t', extrasaction='ignore')
        csv_writer.writeheader()
        for tweet in tweets:
            csv_writer.writerow(tweet)