尝试使用过滤器获得一对多查询,我得到一个错误:
def user_profile(request,pk):
profileObj = Profile.objects.get(id = pk)
topSkill = Profile.skill_set.exclude(description__isnull=True)
otherSkill = Profile.skill_set(description = "")
context = {"profile":profileObj,'topSkills':topSkills,"otherSkills":otherSkills}
return render(request, 'users/user_profile.html', context)
错误:
'ReverseManyToOneDescriptor'对象没有属性'exclude'
我的模型:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, null = True, blank = True)
name = models.CharField(max_length= 500, null = True, blank = True)
email = models.EmailField(max_length= 500, null = True, blank = True)
username = models.CharField(max_length= 500, null = True, blank = True)
location = models.CharField(max_length= 500, null = True, blank = True)
short_intro = models.CharField(max_length= 300, null = True, blank = True)
bio = models.TextField(max_length= 500, null = True, blank = True)
profile_image = models.ImageField(upload_to = "profiles/", default = "profiles/user-default.png", null = True, blank = True)
social_github = models.CharField(max_length= 500, null = True, blank = True)
social_twitter = models.CharField(max_length= 500, null = True, blank = True)
social_linkedIn = models.CharField(max_length= 500, null = True, blank = True)
social_youtube = models.CharField(max_length= 500, null = True, blank = True)
social_website = models.CharField(max_length= 500, null = True, blank = True)
created = models.DateTimeField(auto_now_add = True)
id = models.UUIDField(default = uuid.uuid4, unique = True, primary_key = True, editable = False)
def __str__(self): #Django will call __unicode__ when it needs to render an object in a context where a string representation is needed
return str(self.user.username)
class Skill(models.Model):
owner = models.ForeignKey(Profile,null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length = 200,null=True,blank=True)
description = models.TextField(max_length=500, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False)
def __str__(self):
return str(self.name)
我有以下建议,包括@AbdulAzizBarkat在上述评论中已经提到的建议:
-
最好使用
get_object_or_404()
-
直接从模型中排除项目,而不是使用反向关系。
所以视图应该是:
from django.shortcuts import get_object_or_404
def user_profile(request,pk):
profileObj = get_object_or_404(Profile, id=pk)
topSkill = Skill.objects.exclude(description__isnull=True)
otherSkill = Skill.objects.exclude(description = "")
context = {"profile":profileObj,'topSkills':topSkills,"otherSkills":otherSkills}
return render(request, 'users/user_profile.html', context)
然而,我不理解Skill.objects.exclude(description="")
的逻辑,因为topSkill
已经排除了那些null=True的项目。