簡體   English   中英

Django中過濾數據的問題

[英]Problems with filtering data in Django

我正在發帖,問題是我需要過濾發布最多帖子的用戶列表。 我試過,但只設法過濾了所有帖子,並且遇到了麻煩。

來自用戶的Models.py的字段:

from django.contrib.auth.models import AbstractUser
    
class Usuario(AbstractUser):
        email = models.EmailField(unique=True)
        creation_time = models.TimeField(auto_now_add=True)
        description = models.TextField()
        avatar = models.ImageField(blank=True, null=True, upload_to='autores/', default='img/default.jpg')
        social = models.URLField(blank=True, null=True)
        slug = models.CharField(max_length=60, unique=True, blank=True)
        is_author = models.BooleanField(default=False)

同時在來自博客的models.py

class Post(ModeloBase):
    title = models.CharField('Titulo del Post', max_length=200, unique=True)
    slug = models.SlugField(max_length=200, blank=True, unique=True)
    description = models.TextField('Descripcion')
    author = models.ForeignKey(Usuario, on_delete= models.CASCADE)
    category= models.ForeignKey(Category, on_delete= models.CASCADE)
    content= RichTextField()
    referential_img = models.ImageField('Imagen Referencial', upload_to='imagenes/', max_length=255)
    published= models.BooleanField('Publicado / No Publicado', default=False)
    publication_date = models.DateField('Fecha de Publicacion')
    like = models.ManyToManyField(Usuario, blank=True, related_name='likes')
    dislike = models.ManyToManyField(Usuario, blank=True, related_name='dislikes')

    class Meta:
        verbose_name = 'Post'
        verbose_name_plural = 'Posts'
    
    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)

查看 django 文檔,我嘗試進行過濾,但對我不起作用。 我不知道我的錯誤是什么,所以我希望有人能幫助我。

例如,我的結構可以按類別獲取最近的帖子:

def get(self, request, *args, **kwargs):
        template = 'home.html'
        post_general = Post.objects.filter(state= True, published= True, category= Category.objects.get(name='General')).order_by('publication_date')

        context = {
            'post_general': post_general,
        }
        return render(request, template, context)

你可以嘗試這樣的事情:

Usuario.objects.annotate(num_posts=Count('post')).order_by('-num_post')

如果這不能正確回答您的問題(我在理解它時遇到了一些問題),請參閱Aggregation上的 django 文檔頁面。 這是您想要了解您的目標的地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM