你好我想为玩家实现玩家列表(查询集)和离开战队
的方法我正在寻找类似的东西:
Player.leave_clan([1,2,3])
Player.leave_clan([p1,p2,p3])
我试过的方法是获取account_id列表[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()
答案 0 :(得分:1)
如果您想使用管理器,您可以这样做:
class PlayerManager(models.Manager):
def leave_clan(self, players):
"""
Take a list of player. And removed them from their clan
"""
for player in players:
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()
Player.objects.leave_clan(LIST_PLAYERS)
希望它对你有所帮助。