首页 > 解决方案 > 如何检查页面是否已被访问?(我在用户模型上使用了一个数组字段,我正在尝试在其中添加页面 ID)

问题描述

这不是一个真正的问题,这更像是一个问题,因为我不知道该怎么做。

所以我需要检查一堂课是否已经完成(通过检查该页面是否已在登录帐户上访问过一次)。

我一直在尝试检查该页面是否已被访问。如果没有,则应将 ID 添加到已访问页面的数组中。if 条件如下所示:

if lectie_id in Profile.lectiiRezolvate:
        pass

我得到

argument of type 'DeferredAttribute' is not iterable

.

来自帐户的 models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.postgres.fields import ArrayField

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    xp = models.IntegerField(default=0)
    lectiiRezolvate = ArrayField(models.IntegerField(), null=True)
    exercitiiRezolvate = ArrayField(models.IntegerField(), null=True)
    exercitiiProvocari = ArrayField(models.IntegerField(), null=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

视图.py

from django.shortcuts import render
from django.shortcuts import get_object_or_404
from .models import Lectie
from accounts.models import Profile

def lectii(req):
    lectii = Lectie.objects.all().order_by("id")
    context = {
        'lectii': lectii
    }
    return render(req, '../templates/pagini/lectii-selector.html', context)

def lectie(req, lectie_id):
    if lectie_id in Profile.lectiiRezolvate:
        pass
    lectie2 = get_object_or_404(Lectie, pk=lectie_id)
    lectiePDF = 'lectii/lectia-{}.pdf'.format(lectie2)
    context = {
        'lectiePDF': lectiePDF,
        'lectie2': lectie2
    }
    return render(req, '../templates/pagini/lectii.html', context)

模型.py

from django.db import models

# Create your models here.
class Lectie(models.Model):
    YTLink = models.CharField(max_length = 100)
    capitol = models.IntegerField(null=True)
    cardText = models.CharField(max_length = 250, null=True)
    def __str__(self):
        return str(self.id)

那么如何为每个用户存储他至少访问过一次的课程呢?我想我必须循环进入已解决的课程数组以检查实际课程的 id。如果它不存在,我必须添加它。如果是,什么也不做。

但是正如你所看到的,当我尝试这样做时,我得到了一个错误。

标签: pythondjango

解决方案


我认为您必须手动检查每个对象:

found = False
for profile in Profile.objects.all():
    if lectie_id in profile.lectiiRezolvate:
        found = True
        # logic here


推荐阅读