您好我想实现玩家获取玩家列表(查询集)并离开战队的方法
我正在寻找类似的东西:
Player.leave_clan([1,2,3])
Player.leave_clan([p1,p2,p3])
我尝试的是采用 account_ids [1,2,3] 列表的方法,然后我在查询中使用更新的方法,但在这里我必须只传递帐户 ID
def remove_leavers(self, leavers, clan):
players = Player.objects.filter(account_id__in=leavers)
players.update(clan=None,
previous_clan=clan)
使用我目前的模型,我可以称之为:
leavers = Player.objects.filter(account_id__in=[1,2,3]
for player in leavers:
player.leave_clan()
但我不认为这是正确的做法。我在下面使用以下模型,感谢您的所有建议和建议。我想我需要自定义管理器,但即使在阅读文档后我也不知道如何编写它。
from django.db import models
class Clan(models.Model):
clan_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
tag = models.CharField(max_length=5)
def __str__(self):
return "{tag}".format(tag=self.tag)
@property
def members(self):
return Player.objects.filter(clan=self)
def kick_player(self, player):
player.leave_clan()
class Player(models.Model):
account_id = models.IntegerField(primary_key=True)
account_name = models.CharField(max_length=250)
clan = models.ForeignKey('Clan',
on_delete=models.CASCADE,
blank=True,
null=True,
related_name='current_clan')
previous_clan = models.ForeignKey('Clan',
on_delete=models.CASCADE,
blank=True,
null=True,
related_name='previous_clan')
def __str__(self):
return '{0} - {1}'.format(self.account_name, self.account_id)
def leave_clan(self):
self.previous_clan = self.clan
self.clan = None
self.save()