如何仅从用户名访问帖子?

时间:2018-12-28 11:13:22

标签: django django-models django-views

我正在编写模型,我想直接在django视图中从用户名访问帖子。可能吗? 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.utils import timezone

#this is how profile of a sample user, say MAX looks like
class Profile(models.Model):
    Follwers=models.IntegerField(default='0')
 user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True)
    bio=models.TextField(max_length=120,blank=True)
    location=models.CharField(max_length=30,blank=True)
    birth_date=models.DateField(null=True,blank=True)
    verified=models.BooleanField(default=False)
 ProfilePic=models.ImageField(upload_to='UserAvatar',blank=True,null=True)

    def __str__(self):
        return self.user.username

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

class post(models.Model):
    Profile=models.ForeignKey(Profile,on_delete=models.CASCADE)
    Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True)
    DatePosted=models.DateTimeField(default=timezone.now)
    Content=models.TextField(blank=True,null=True)

    def __str__(self):
        return self.Profile.user.username

1 个答案:

答案 0 :(得分:0)

您可以将其添加到视图中,

def get_queryset(self):
    return post.objects.filter(Profile__user__username=self.kwargs['username'])

根据您的kwarg,用户名或pk对其进行修改。