【问题标题】:Annotate querying, pk注释查询,pk
【发布时间】:2022-01-02 00:50:46
【问题描述】:

pk和annotate一起使用应该如何查询?

当客人点击链接时,我需要重定向到用户个人资料。

型号

class Posty(models.Model):
   title = models.CharField(max_length=250, blank=False, null=False, unique=True)
   sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True)
   content = models.TextField(max_length=250, blank=False, null=False)
   image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])])
   author = models.ForeignKey(Profil, on_delete=models.CASCADE)
   updated = models.DateTimeField(auto_now=True)
   published = models.DateTimeField(auto_now_add=True)
   T_or_F = models.BooleanField(default=False)
   likes = models.ManyToManyField(Profil, related_name='liked')
   unlikes = models.ManyToManyField(Profil, related_name='unlikes')
   created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE)

class CommentPost(models.Model):
   user = models.ForeignKey(Profil, on_delete=models.CASCADE)
   post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments")
   content1 = models.TextField(max_length=250, blank=False, null=False)
   date_posted = models.DateTimeField(default=timezone.now)
   date_updated = models.DateTimeField(auto_now=True)

def __str__(self):
    return str(self.content1)

class Profil(models.Model):
   first_name = models.CharField(max_length=50)
   last_name = models.CharField(max_length=50)
   age = models.PositiveIntegerField(blank=True, null=True)
   country = models.CharField(max_length=50)
   user = models.OneToOneField(Account, on_delete=models.CASCADE)
   avatar = models.ImageField(default="avatar.png", upload_to="images",validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
   slug = models.SlugField(blank=True)
   gender = models.CharField(max_length=6, choices=GENDER)
   friends = models.ManyToManyField(Account, blank=True, related_name="Friends")
   social_facebook = models.CharField(max_length=250, null=True, blank=True)
   social_instagram = models.CharField(max_length=250, null=True, blank=True)
   social_twitter = models.CharField(max_length=250, null=True, blank=True)
   social_youtube = models.CharField(max_length=250, null=True, blank=True)
   social_linkedin = models.CharField(max_length=250, null=True, blank=True)
   updated = models.DateTimeField(auto_now=True)
   created = models.DateTimeField(auto_now_add=True)

观看次数

   if tag == None:
    my_tag = Posty.objects.annotate(
        latest_comment = Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('content1').order_by('-date_posted')[:1]),
        my_author=Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('user__user__username').order_by('-date_posted')[:1]),
    )

我的用户名正确,但我无法获得正确的重定向:

【问题讨论】:

  • 请移除图片并添加实际模板代码。

标签: django redirect request primary-key


【解决方案1】:

不幸的是,您需要使用查询集注释CommentPostid 信息,就像添加username 信息一样。最终会在原始查询集中添加大量子查询。相反,我建议使用prefetch relatedCommentPost 信息与原始查询集一起预加载(用于减少数据库命中)并直接从模板访问该信息。例如:

# view
my_tag = Posty.objects.prefetch_related('commentpost_set')

# template
{% for post in my_tag %}
    <span><a href="{% url 'home:detail_post' post.pk %}"> {{post.commentpost_set.last.content1}}</a><span>
    <span><a href="{% url 'home:detail_post' post.commentpost_set.last.user.pk %}"> {{post.commentpost_set.last.user.username}}</a><span>
{% endfor %}

另外,last 是一个查询集函数,它返回给定查询集的最后一个对象。我可以通过reverse queryingPosty 对象访问CommentPost 查询集。

【讨论】:

  • 谢谢,但是阅读正确重定向到个人资料时出现问题。我试过 {% url 'home:detail_post' post.cmets.last.user.pk %} 因为我的related_name 是“cmets”
  • 预期结果是什么,您目前得到了什么(您被重定向到哪个配置文件)?也请分享重定向视图。
  • 未找到带有参数 '('',)' 的 'profil_uzytkownika' 的反向。尝试了 1 种模式:['profile/profil_uzytkownika/(?P[0-9]+)/$']。我添加了一个模型 Profil
  • 这意味着它没有从用户对象中获取任何 ID。如果有任何数据,请查看数据库。否则尝试在模板中调试它。
  • 我怎样才能很好地在数据库中移动?如何轻松读取连接?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 2017-09-10
  • 2020-01-18
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
相关资源
最近更新 更多