F()使用Django表达奇怪的行为

时间:2015-05-23 19:44:07

标签: python django django-models django-templates django-template-filters

我有这个模板标记,最终返回“有效”广告列表(检查活动字段的广告系列是否为True,然后使用查询集从广告系列中提取广告)

@register.assignment_tag
def get_current_campaigns(amount):

    # Get all the campaigns that are active 
    current_campaigns = Campaign.objects.filter(active=True)

    current_campaigns_count = current_campaigns.count()

    # To avoid the list index being out of range and throwing an IndexError
    # We reduce the amount to match the amount of rows in the model if the
    # amount of rows is less than the amount being requested.
    if amount > current_campaigns_count:
        amount = current_campaigns_count

    # Select active campaigns randomly
    random_camps = []
    for i in range(amount):
        random_camps.append(random.choice(current_campaigns))

    # prepare all the ads to return 
    output = []
    for campaign in random_camps:
        # get all the ads that a campaign has 
        ads = campaign.advertisement_set.all()
        # now select one randomly
        ad = random.choice(ads)
        # hand it to output 
        output.append(ad)
        # mark that this campaign has been seen
        campaign.impressions = F('impressions') + 1
        campaign.save()
        # checks and sets if the campaign is still active
        campaign.check_active()

    return output

以下是与之相关的模型:

class Campaign(models.Model):
    ''' Represents an Advertisement Campaign '''
    title = models.CharField(max_length=50, blank=True, verbose_name='Campaign Title')
    impressions = models.IntegerField()
    impression_limit = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    def check_active(self):
        ''' Checks if the Campaign is currently active '''
        if self.impressions >= self.impression_limit:
            self.active = False
            self.save()

奇怪的一点:每当我访问该页面时,广告都会打开,然后在管理员中进行检查,对象展示次数会增加2(应为1)并标记为False,即使此{{1不是这样,它仍然以某种方式将活动字段更改为if self.impressions >= self.impression_limit,无论如何。

任何线索为什么会发生这种奇怪的行为?如果需要,我可以提供更多信息。

1 个答案:

答案 0 :(得分:4)

random.choice不保证生成非重复项目。

import random

random_camps = random.sample(current_campaigns, amount)

是去这里的方式。

<强>更新 如果你担心速度,this question可以解决postgres中的快速随机行选择。

相关问题