python 获取模型对象返回的匹配查询不存在

vybvopom  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(164)

我想显示当其他用户访问他的public_profile页面时,从Book模型发布的用户,为此,我必须使用此方法:

def public_profile(request, slug):
    profile = get_object_or_404(Profile, slug=slug)
    book = Book.objects.get(slug=slug)
    context = {
        'profile': profile,
        'book': book
    }
    return render(request, 'public_profile.html', context)

但使用该方法返回:public_profile模板中的Book matching query does not exist.
public_profile页面:

<p class="title is-4"><a href="{{ book.get_user_public_url }}">
     {{ book.user }}
</a></p>

我的模型

class Book(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    audio = models.FileField(upload_to='audio')
    title = models.CharField(max_length=50)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='audio-image')
    introduction = models.TextField(max_length=500)
    slug = models.SlugField(unique=True)

    def get_user_public_url(self):
        return reverse('Public-Profile', kwargs={'slug': self.user.profile.slug})

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,  on_delete=models.CASCADE)
    profile_photo = models.ImageField(upload_to='profile-image', default='static/dafault.jpg')
    twitter = models.URLField(blank=True, null=True, unique=True)
    website = models.URLField(blank=True, null=True, unique=True)
    linkedln = models.URLField(blank=True, null=True, unique=True)
    country = models.CharField(max_length=70, blank=True, null=True,)
    about = models.TextField(max_length=700, blank=True, null=True)
    slug = models.SlugField(max_length=100, unique=True)
7vux5j2d

7vux5j2d1#

问题是我试图使用slug=slug获取Book对象,这与检索Profile对象所使用的参数相同。然而,slug是Book对象的唯一字段,因此我实际上试图使用错误的字段检索Book对象。
为了解决这个问题,我尝试使用下面的方法:

def public_profile(request, slug):
    profile = get_object_or_404(Profile, slug=slug)
    book = Book.objects.get(user=profile.user)
    context = {
        'profile': profile,
        'book': book
    }
    return render(request, 'public_profile.html', context)

但我得到了这个错误:get return more than one Book --it returned 2!因为@WillemVanOnsem在评论区说:what is book supposed to be? It is not said that the profile has any book, and it is also possible that it has multiple books.表示:在我的数据库中有两个或多个Book对象,它们与我试图检索的Profile对象关联的User对象具有相同的user值。
所以我把代码改成这样:

def public_profile(request, slug):
    profile = get_object_or_404(Profile, slug=slug)
    books = Book.objects.filter(user=profile.user)
    context = {
        'profile': profile,
        'books': books
    }
    return render(request, 'public_profile.html', context)

并使用以下命令为该用户获取Book

{% for book in books %}
    <p class="title is-4">
        {{ book.title }}
    </p>
{% endfor %}

相关问题