如何在Django中加载JSON数据并创建模型



我正在尝试加载json数据文件并创建给定json数据文件的播放器类。我查阅了Django网站上的文档和一些关于堆栈溢出的帖子,但不知道该怎么做。当我尝试在models.py上创建create()的类方法时,我一直得到没有表存在的错误。有人能帮我弄明白吗?提前谢谢你

对于models.py,我有播放器类

class Player(models.Model):
pos = models.CharField(max_length=2, default="")
name = models.CharField(max_length=30, default="")
age = models.PositiveIntegerField()
posRank = models.PositiveIntegerField()
throwAtt = models.PositiveIntegerField()
throwYd = models.PositiveIntegerField()
throwTD = models.PositiveIntegerField()
interception = models.PositiveIntegerField()
rushAtt = models.PositiveIntegerField()
rushYd = models.PositiveIntegerField()
rushTD = models.PositiveIntegerField()
rushAvgYd = models.FloatField()
target = models.PositiveIntegerField()
rec = models.PositiveIntegerField()
recYd = models.PositiveIntegerField()
recAvgYd = models.FloatField()
recTD = models.PositiveIntegerField()
totalTD = models.PositiveIntegerField()
fumble = models.PositiveIntegerField()
fpts = models.FloatField(null=True)
ppr = models.FloatField()
totGames = models.PositiveIntegerField()

和serializer .py我有播放器序列化程序如下所示

class PlayerSerializer(serializers.ModelSerializer):
class Meta:
model = Player
fields = ('name', 'pos', 'age', 'posRank', 'throwAtt', 'throwYds', 'throwTD',
'interception', 'rushAtt', 'rushYd', 'rushTD', 'rushAvgYd', 'target',
'rec', 'recYd', 'recAvgYd', 'recTD' 'totalTD', 'fumble', 'fpts', 'ppr', 'totGames')

and inside views.py i have this class
class PlayerView(generics.CreateAPIView):
players = Player.objects.all()
serializer = PlayerSerializer(players, many=True)
def get(self, request):
output = json.load('api/NewNFLdata.json')
for player in output:
newPlayer = Player(pos=player["FantPos"],
name=player["Player"],
age=player["Age"],
posRank=player["PosRank"],
throwAtt=player["Att"],
throwYd=player["Yds"],
throwTD=player["TD"],
interception=player["Int"],
rushAtt=player["Att.1"],
rushYd=player["Yds.1"],
rushTD=player["TD.1"],
rushAvgYd=player["Y/A"],
target=player["Tgt"],
rec=player["Rec"],
recYd=player["Yds.2"],
recAvgYd=player["Y/R"],
recTD=player["TD.2"],
totalTD=player["TD.3"],
fumble=player["Fmb"],
fpts=player["FantPt"],
ppr=player["PPR"],
totGames=player["G"]
)
newPlayer.save()
return Response(serializer.data)

我试着自己查找堆栈溢出但无法找到一种方法加载json数据到模型

看一下fixture:https://docs.djangoproject.com/en/3.1/howto/initial-data/

如果你能把JSON文件调整到合适的格式,你就能从Django的fixture加载过程中获益,其中包括你不需要编写的字段验证。好运!

相关内容

  • 没有找到相关文章

最新更新