我正在尝试创建一个类似于幻想的应用程序,我希望用户每次添加一名球员时,开始的11名都增加,而球队预算却要减少该球员的价格。
我正在将django网络框架用于python。
这是我的用户团队模型
class UserTeam(models.Model):
name = models.CharField(max_length=50)
user = models.OneToOneField(User, on_delete=models.CASCADE, default=None)
players = models.ManyToManyField(Player)
budget = models.IntegerField(default=100000000)
FORMATION_CHOICES = (
('4-3-3', '4-DEF 3-MID 3-ATT'),
('4-4-2', '4-DEF 4-MID 2-ATT'),
('3-4-3', '3-DEF 4-MID 3-ATT'),
('5-3-2', '5-DEF 3-MID 2-ATT'),
)
formation = models.CharField(max_length=10, choices = FORMATION_CHOICES)
starting_xi = models.IntegerField(default=0)
bench_sub = models.IntegerField(default=0)
total_score = models.IntegerField(default=0)
round_score = models.IntegerField(default=0)
Highest_team_score = models.IntegerField(default=0)
@classmethod
def transfer_player_in(cls, user, new_player):
team, created = cls.objects.get_or_create(
user=user
)
team.players.add(new_player)
@classmethod
def transfer_player_out(cls, user, new_player):
team, created = cls.objects.get_or_create(
user=user
)
team.players.remove(new_player)
我的播放器型号
class Player(models.Model):
POSITION_CHOICES = (
('ATT', 'Attacker'),
('MID', 'Midfielder'),
('DEF', 'Defender'),
('GK', 'GoalKeeper'),
)
name = models.CharField(max_length=50)
FirstName = models.CharField(max_length=20)
LastName = models.CharField(max_length=20)
position = models.CharField(max_length=3, choices = POSITION_CHOICES)
country = models.ManyToManyField(Country)
photo = models.ImageField(blank=True)
price = models.IntegerField(default=0)
total_score = models.IntegerField(default=0)
这是查看功能,用于处理球员进出的转移
def Transfer_Player(request, operation, pk):
player= Player.objects.get(pk=pk) #gets a particular player into the variable player
if operation =='add': #if user wants to buy player
UserTeam.starting_xi += 1
UserTeam.budget = UserTeam.budget - Player.price
UserTeam.transfer_player_in(request.user, player) #add player to team
UserTeam.save
elif operation =='sell':
UserTeam.transfer_player_out(request.user, player)
else:
pass
return redirect('/Fantasy')
我希望用户的开始11每次执行加法操作时都会增加1,并且用户预算会因播放器的价格而减少,但相反却会收到TypeError,即+ =不支持的操作数类型:“ DeferredAttribute”和“ int”。
答案 0 :(得分:0)
您需要具有UserTeam
的具体实例才能执行所需的操作。我怀疑您的代码应如下所示:
if operation =='add': #if user wants to buy player
team = UerTeam.objects.get(user_id=request.user.id)
team.starting_xi += 1
team.budget -= player.price
team.save()
UserTeam.transfer_player_in(request.user, player) #add player to team