使用select_related和prefetch_related

时间:2017-04-04 12:26:19

标签: django models prefetch django-select-related

这是我的两个模型类

class UserProfile(models.Model):
    user=models.OneToOneField(User)
    profile_pic=models.ImageField(upload_to='profilepics/%Y/%m/%d/',default='\LoginPage\images\default.jpg')
def __unicode__(self):
    return self.user.username

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

class Video(models.Model):
    username=models.ForeignKey(UserProfile,on_delete=models.CASCADE,default="",related_name='uservideos')
    video=models.FileField(upload_to='videos/%Y/%m/%d/',default='')
    videotitle=models.CharField(max_length=100)
    likes=models.PositiveIntegerField(default=0)
    dislikes=models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.video.url

这是我的视图功能,我想使用select_related选择并显示特定用户的所有视频但我收到错误

'的FileDescriptor'对象没有属性' select_related'

def usermainview(request):
    username=request.POST['username']
    tempuser=User.objects.get(username=username)
    videolist=Video.video.select_related('user').get(username=tempuser)
    return render(request,'AfterLogin/main.html',{'videolist':videolist})

0 个答案:

没有答案