简体   繁体   English

如何根据特定用户 model 字段过滤 django 中的帖子对象?

[英]How to filter post objects in django according to a particular user model field?

I'm currently creating a Social platform with Django.我目前正在使用 Django 创建一个社交平台。 Right now, I'm developing homepage and want to show posts matching a userfield.现在,我正在开发主页并希望显示与用户字段匹配的帖子。 This is my Post model:这是我的帖子 model:

class Discussion(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Account, on_delete=models.CASCADE)
    post = models.TextField()
    date = models.DateTimeField(default=timezone.now)

This is user account model:这是用户帐户 model:

class Account(AbstractBaseUser):
    email = models.EmailField(verbose_name='email', max_length=60, unique=True)
    username = models.CharField(max_length=30, unique=True)
    classid = models.CharField(max_length=10)

This is view:这是视图:

@login_required(login_url='login')
def home(request):
    if request.method == 'GET':
        discussions = Discussion.objects.get(post=Account.classid).order_by('-date')
        form = PostDiscussionForm()
        return render(request, 'app/home.html', {'discussions':discussions,'form':form})

    else:
        form = PostDiscussionForm(request.POST)
        newdisscussion = form.save(commit=False)
        newdisscussion.author = request.user
        newdisscussion.save()
        return redirect('home')

I want to show only logged users matching their classid (from user account model)我只想显示与他们的 classid 匹配的登录用户(来自用户帐户模型)

What I gather from here, is that you want to show which users are currently online/logged in?我从这里收集到的是,您想显示哪些用户当前在线/登录? For that you'll need to store additional information when logging like, add a boolean field in the user model indicating whether or not the user has logged in and then filter based on that field.为此,您需要在登录时存储其他信息,例如在用户 model 中添加一个 boolean 字段,指示用户是否已登录,然后根据该字段进行过滤。

class Account(AbstractBaseUser):
    email = models.EmailField(verbose_name='email', max_length=60, unique=True)
    username = models.CharField(max_length=30, unique=True)
    logged_in = models.BooleanField(default=False)
    classid = models.CharField(max_length=10)

Now add additional logic which sets this field to true when the user eventually logs in from your /login route.现在添加额外的逻辑,当用户最终从您的/login路由登录时,将此字段设置为 true。

Then Filter using:然后过滤使用:

$ return Account.objects.filter(logged_in==True)

This will return you all users that have currently logged in, if you're not using any serializers , than use value_list for getting the values only rather than the whole user objects.如果您没有使用任何serializers程序,这将返回所有当前已登录的用户,而不是使用value_list仅获取值而不是整个用户对象。

$ return Account.objects.filter(logged_in==True).values_list('classid', flat=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM