筛选数据集没有值 [英] filter dataset not having a value

查看:111
本文介绍了筛选数据集没有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有如下所示的模式:

Suppose i have a schema like below :

Book | Author
-------------
 B1  |   A1
 B1  |   A3
 B1  |   A2

 B2  |   A5 
 B2  |   A4
 B2  |   A3

 B3  |   A5
 B3  |   A6
 B3  |   A1

 B4  |   A1
 B4  |   A5
 B4  |   A6

具有以下型号:

class Books(models.Model):
    author = models.CharField(
        max_length=100,
        blank=False,
        null=False,
        db_index=True,
        verbose_name=_('authors'),
    )
    book = models.CharField(
        max_length=50,
        blank=False,
        null=False,
        db_index=True,
        verbose_name=_('book'),
    )

    book_type = models.CharField(
        max_length=50,
        blank=False,
        null=False,
        default="regular"
    )

    flavour = models.CharField(
        max_length=10,
        blank=False,
        null=False,
        verbose_name=_('flavour'),
    )
    cost = models.IntegerField()
    status = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        db_index=True,
    )

,我想过滤出所有作者为 not A1(在这种情况下为 B2

and i want to filter out all those book whose author is not A1 (B2 in this case)

这是使用 group by的简单SQL 没有子句,我很难过的是使用Django queryset和注释完成它。在 count 附近,大多数注释工作都无法解决这种特殊情况。

This is simple SQL using group by and not having clause, what i am having tough time is getting it done usinng django queryset and annotate. Most of the annotate work around count which i am not able to fit in this particular case.

任何指针都是有用的,谢谢! :)

any pointers is helpful, thanks! :)

推荐答案

这应该做您想做的事情:

This should do what you want:

Books.objects.exclude(author='A1')

如果您需要一个 book 值的独特列表,然后可以执行以下操作:

If you want a distinct list of book values then you can do:

Books.objects.exclude(author='A1').values_list('book').distinct()

您的 Books 模型对我来说有点奇怪。不知道您的具体用例是什么,但似乎 Book 模型与 ManyToMany 关系与作者可能更合适。

Your Books model looks a little strange to me though. Not sure what your specific use case is, but it seems that a Book model with a ManyToMany relationship to an Author might be more appropriate.

这篇关于筛选数据集没有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆