从ManyToManyField数据在ForgeinKey上添加数据时,“无法通过模型实例访问Manager”

时间:2019-08-01 19:29:12

标签: django django-models django-views

在型号中:

class MyTeam(models.Model):
    captain_first_team = models.ForeignKey(FirstTeamPlayer, on_delete=models.SET_NULL, null=True, blank=True, related_name="captain_first_team_set")
    team_player_first_team = models.ManyToManyField(FirstTeamPlayer, blank=True, related_name="team_player_first_team_set")

在视图中:

amar_team = get_object_or_404(MyTeam, pk=team_id)
first_team_player = get_object_or_404(amar_team.team_player_first_team, pk=player_id)
amar_team.objects.create(captain_first_team=first_team_player)

在这里,在MyTeam模型中,我有ManyToManyField字段和ForeignKey字段。我想从ManyToManyField字段数据中将数据添加到ForeignKey字段中。

我也尝试:

amar_team.captain_first_team.add(first_team_player)
amar_team.captain_first_team.save(first_team_player)

但是它不起作用。我该怎么办?

1 个答案:

答案 0 :(得分:0)

就像错误所述一样,您不能通过模型* instance8访问.objects。仅通过模型类。

因此,您应该将其定义为:

MyTeam.objects.create(captain_first_team=first_team_player)

,而不是通过 amar_team.objects.create(...)

但是,根据您的评论,您想要更新captain_first_team中的amar_team,因此可以将外键设置为:

amar_team = get_object_or_404(MyTeam, pk=team_id)
first_team_player = get_object_or_404(amar_team.team_player_first_team, pk=player_id)
amar_team.captain_first_team = first_team_player
amar_team.save()