【发布时间】:2021-04-23 07:19:04
【问题描述】:
我正在尝试加载 json 数据文件并使用给定的 json 数据文件创建 Player 类。 我查看了 Django 网站上的文档和一些关于堆栈溢出的帖子,但不知道该怎么做。 当我尝试在 models.py 上创建 create() 的类方法时,我一直收到 no table exists 错误。 谁能帮我弄清楚??提前谢谢你
对于 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()
对于serializers.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,你不需要从头实现,搜索
Django文档Fixure -
当我尝试加载夹具时,我是否必须具有与序列化程序类中定义的字段相同的键值?
-
你想只加载一次json数据还是需要在你的应用程序中导入功能,以便用户能够通过导入json文件来加载数据?
-
@JaewooCho 见this
-
Fixtures 有一个固定的结构,研究它然后应用它,你的答案是否定的,fixtures 是模型相关的,而不是序列化器相关的(django,不是 DRF)
标签: python json django django-rest-framework backend