F()表达式与Djang的奇怪行为

2024-05-19 15:21:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模板标签,它最终返回一个“活动”广告列表(检查活动字段的活动是否为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,即使这个if self.impressions >= self.impression_limit不是真的,它仍然会以某种方式将活动字段更改为False。你知道吗

你知道为什么会有这种奇怪的行为吗?我可以提供更多的信息,如果需要的话。你知道吗


Tags: theselftrueifmodelscountrandomcurrent
1条回答
网友
1楼 · 发布于 2024-05-19 15:21:15

random.choice不保证生成非重复项。你知道吗

import random

random_camps = random.sample(current_campaigns, amount)

是去这里的路。你知道吗

更新 如果您担心速度,那么this question会解决postgres中的快速随机行选择问题。你知道吗

相关问题 更多 >