我如何让以下工作?
player = Player.objects.get(pk=player_id)
game = Game.objects.get(pk=game_id)
game_participant = GameParticipant.objects.filter(player=player, game=game)
game_participant.save()
当对象已存在于数据库中时,我得到:
'QuerySet'对象没有属性'save'。
就我的模型而言,GameParticipant
对ForeignKey
和Game
都有Player
。我理解过滤器会返回一个QuerySet,但我不确定如何将其转换为GameParticipant
或者这不是正确的想法?
class Player(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
class Game(models.Model):
game_date = models.DateTimeField()
team = models.ForeignKey(Team)
description = models.CharField(max_length=100, null=True, blank=True)
score = models.CharField(max_length=10, null=True, blank=True)
class GameParticipant(models.Model):
STATUS_CHOICES = (('Y','Yes'),('N','No'),('M','Maybe'))
status = models.CharField(max_length=10, choices=STATUS_CHOICES)
game = models.ForeignKey(Game)
player = models.ForeignKey(Player)
或者有更好的方法做我想做什么?即。使用.get()而不是.filter()然后我遇到其他问题???
答案 0 :(得分:15)
由于您正在处理多个对象,因此您需要使用update
方法:
https://docs.djangoproject.com/en/2.0/topics/db/queries/#updating-multiple-objects-at-once
答案 1 :(得分:14)
过滤器会返回一个查询集。查询集不是单个对象,它是一组对象,因此在查询集上调用save()没有意义。而是保存每个单独的对象 IN 查询集:
game_participants = GameParticipant.objects.filter(player=player, game=game)
for object in game_participants:
object.save()
答案 2 :(得分:1)
通过将未保存的对象分配给另一个对象外部字段,可以获得此错误。
for project in projects:
project.day = day
day.save()
以及正确方法:
day.save()
for project in projects:
project.day = day
答案 3 :(得分:0)
def Clearlist(request):
que = Feeds.objects.filter(selected=True)
for i in que:
i.selected = False
i.save()
return redirect('core:all')
这是将a保存到查询集中的好方法
答案 4 :(得分:0)
Django 2.2的新功能:bulk_update
objs = [
Entry.objects.create(headline='Entry 1'),
Entry.objects.create(headline='Entry 2'),
]
objs[0].headline = 'This is entry 1'
objs[1].headline = 'This is entry 2'
Entry.objects.bulk_update(objs, ['headline'])
答案 5 :(得分:0)
当您使用queryset时,它可能会返回一个列表,说明您为什么要使用
game_participant = GameParticipant.objects.filter(player=player, game=game)[0]
代替
game_participant = GameParticipant.objects.filter(player=player, game=game)
尝试一下对我有用
答案 6 :(得分:0)
过滤器返回一个列表,如果您要从中获取特定的单个对象,则需要提供该对象的索引
game_participant = GameParticipant.objects.filter(player=player, game=game)[0]