我有模特:
class Participant(models.Model):
user = models.CharField(max_length=20)
date = models.DateTimeField()
def __unicode__(self):
return self.user
class Winner(models.Model):
phone_no = models.CharField(max_length=20)
win_date = models.DateTimeField()
def __unicode__(self):
return self.user
在这里,我想要的是从我的参与者模型中随机产生一个赢家。
我想检查随机生成的赢家过去是否赢得过比赛,然后我想检查上次和现在之间的赢奖日期差是否大于4个月。如果更大,则用户可以赢得游戏,否则将再次生成随机用户。
为此,我已经完成了:
player_list = Participant.objects.all()
winner = random.choice(player_list)
next_check = Winner.objects.filter(user=winner)
if next_check:
if (date.today() - timedelta(days= 4*365/12)) > next_check.win_date.date():
#what if the user has won 5 times in past
final_winner = winner
else:
# Again generate winner randomy and again check for the date is greater than 4 month
我已经这样做了:
final_winner = None
while not final_winner:
winner = random.choice(player_list)
next_check = Winner.objects.filter(user=winner)
if next_check:
#wht if the user has won previously and what if the user has won many times previously
if (date.today() - timedelta(days= 4*365/12)) > next_check.win_date.date():
final_winner = winner
谁能指导我做到这一点。
谢谢
首先,您的模型层次结构设计不当。无论Participant
和Winner
模型起到类似的目的,并且具有相同的字段。
而且,这似乎Participant
是一个超集,Winner
因为首先将每个人都定义为参与者,而不是其中一个将赢得比赛并成为赢家。所以,我建议你创建Winner
通过继承从Participant
和像下面的超类中定义相同的字段:
class Participant(models.Model):
user = models.ForeignKey('auth.User')
creation_date = models.DateTimeField()
phone_no = models.CharField(max_length=20)
def __unicode__(self):
return self.user.email
class Winner(Participant):
win_date = models.DateTimeField()
关于此方法的一个美丽之处在于,Django将创建一个OneToOneField
从获胜者到参与者的隐式字段,因此您将自动直接连接到获胜者的参与者详细信息。
关于您的实际问题,关于检查用户在最近4个月内是否赢得过任何游戏,您可以执行以下操作:
from datetime import timedelta
from django.utils.timezone import now
def has_won_any_game_since(user, period):
return Winner.objects.filter(user=user, win_date__gt=now() - period).exists()
def get_random_winner():
player_list = list(Participant.objects.all())
four_months = timedelta(days=120) # ~4 months
while len(player_list) > 0:
player = random.choice(player_list)
if not has_won_any_game_since(player.user, four_months):
return player
else:
player_list.remove(player)
else:
return None
>>> winner = get_random_winner()
<Winner: [email protected], win_date='07/23/2014 07:23:86'> # win_date is supposed to be less than 120 days.
希望这可以帮助。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加