首页 \ 问答 \ Django查询不分组(Django query does not group)

Django查询不分组(Django query does not group)

我想按收件人用户分组消息数量 - > {'User 1':5}; {'User 2':7} ...

我的模特:

class Mensaje(models.Model):
    remitente = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='Remitente')
    destinatario = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='Destinatario')
    mensaje = models.TextField(validators=[MaxLengthValidator(1000)]) 
    leido = models.BooleanField(default=False)
    fechaEnvio = models.DateTimeField(auto_now_add=True)

我的查询:

 mensajes = Mensaje.objects.filter(destinatario=request.user).values('pk', 'remitente__username').annotate(num_msg=Count('pk')).order_by('-fechaEnvio')

结果:

{'pk': 28, 'remitente__username': 'Paco', 'num_msg': 1}, {'pk': 27, 'remitente__username': 'Paco', 'num_msg': 1}, {'pk': 26, 'remitente__username': 'jota', 'num_msg': 1}, {'pk': 25, 'remitente__username': 'jota', 'num_msg': 1}...

如您所见,查询返回所有没有用户分组的消息。

另一个问题:为什么不工作mensajes = request.user.mensaje_set.all()


I want to group the number of messages by recipient user -> {'User 1': 5};{'User 2': 7}...

My model:

class Mensaje(models.Model):
    remitente = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='Remitente')
    destinatario = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='Destinatario')
    mensaje = models.TextField(validators=[MaxLengthValidator(1000)]) 
    leido = models.BooleanField(default=False)
    fechaEnvio = models.DateTimeField(auto_now_add=True)

My query:

 mensajes = Mensaje.objects.filter(destinatario=request.user).values('pk', 'remitente__username').annotate(num_msg=Count('pk')).order_by('-fechaEnvio')

Result:

{'pk': 28, 'remitente__username': 'Paco', 'num_msg': 1}, {'pk': 27, 'remitente__username': 'Paco', 'num_msg': 1}, {'pk': 26, 'remitente__username': 'jota', 'num_msg': 1}, {'pk': 25, 'remitente__username': 'jota', 'num_msg': 1}...

As you can see, the query returns all the messages without group by user.

Another question: Why does not work mensajes = request.user.mensaje_set.all()?


原文:https://stackoverflow.com/questions/49019609
更新时间:2023-11-24 12:11

最满意答案

反过来:

  1. getDept(int &d)与其描述一致,但getSalary(double *d)并不完全:描述说它应该将值复制到函数参数指向的int变量中。

    然后getSalary应该采用int *参数而不是double *参数,并且该方法应该执行适当的getSalary 。 (这确实看起来有点奇怪 - 确定它不是说双重而不是int?)

  2. 从手头的信息来看,没有什么可以清理的,假设成员变量只是intdouble s等等。 有指针的成员吗?

In turn:

  1. getDept(int &d) is consistent with its description, but getSalary(double *d) isn't quite: the description says it should copy the value into the int variable pointed to by the function argument.

    getSalary then should take a int * argument, instead of a double * argument, and the method should perform the appropriate cast. (This does seem a bit of an odd specification though — sure it wasn't meant to say double rather than int?)

  2. From the information at hand, there is nothing to clean up, presuming the member variables are just ints and doubles and so on. Are there any members that are pointers?

相关问答

更多
  • 只需使用std::vector> 。 移动时的std::function几乎总是很便宜。 为了使它不便宜,存储的函数对象必须(A)小,(B)具有无除外移动构造函数并且(C)移动昂贵。 有目的地写这样的对象并不难,但很难不小心写一个。 现在,标准没有规定多小; 例如,对于MSVC,他们将其设置为一个或两个std::string s的大小。 几乎可以肯定,管理原始指针的开销会使你的代码比使用这里的值更差,性能更差。 两者都是因为你将燃烧精神资源来修复原始指针错误 ...
  • A的析构函数在其生命周期结束时运行。 如果你希望它的内存被释放并且析构函数运行,你必须删除它,如果它被分配在堆上。 如果它被分配在堆栈上,这会自动发生(即当它超出范围时;见RAII)。 如果它是一个类的成员(不是一个指针,而是一个完整的成员),那么当包含的对象被销毁时,这将会发生。 class A { char *someHeapMemory; public: A() : someHeapMemory(new char[1000]) {} ~A() { delete[] someHe ...
  • 不,析构函数按照相反的顺序自动调用。 (基础班最后)。 不要调用基类析构函数。 No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.
  • 关于第二个问题,第二个调用注册为int&因为它可以选择履行该签名。 文字只能通过值传递,而变量可以通过引用或值传递。 因此0只能匹配采用int签名,而bW可以匹配采用int或int&签名。 关于第一个问题,你确定你已经完全从sdlWrapper.hpp复制了这两行吗? 它看起来不像候选人的签名与你提供的签名相匹配。 With regard to the second question, the second call registers as an int& because it has the optio ...
  • 反过来: getDept(int &d)与其描述一致,但getSalary(double *d)并不完全:描述说它应该将值复制到函数参数指向的int变量中。 然后getSalary应该采用int *参数而不是double *参数,并且该方法应该执行适当的getSalary 。 (这确实看起来有点奇怪 - 确定它不是说双重而不是int?) 从手头的信息来看,没有什么可以清理的,假设成员变量只是int和double s等等。 有指针的成员吗? In turn: getDept(int &d) is consis ...
  • 我相信你在这里要做的就是破坏一个单身对象。 它可以在单线程环境中完成如下: void TsDatabasePool::Destroy() { if (objInst_) { delete objInst_; objInst_= 0x0; } } 理想情况下,您可以使用类似shared_ptr的东西来确保对象保持不变,直到没有人再需要它为止。 I believe what you are trying ...
  • _initterm和_initterm_e (msdn _initterm_e注释声明错误 - 实际上它使用_PIFV类型)由不同的CRT dll导出。 它也在lib文件中声明。 并且这个函数的实现非常简单: typedef void (__cdecl *_PVFV)(); void _initterm(const _PVFV *ppfn, const _PVFV *end) { do { if (_PVFV pfn = *++ppfn) { ...
  • 不,重复使用对象的内存并不危险,只要你正确地做到了。 而且,你不必限制自己没有指针的对象:通过明确地调用析构函数,你可以准备对象以供重用,就像这样: Foo* foo = new Foo; // Do something with foo // Done with foo, writing a new version of foo on top of the old one. foo->~Foo(); // Call the destructor explicitly to clean up the ...
  • 您的问题是签名不匹配。 它应该是这样的: int operator()(Node* const & lhs, Node* const & rhs) const { return compare(lhs, rhs); } 问题是const最终应用的地方。 你可以通过说typedef Node * base_T_arg_t;来完成同样的事情typedef Node * base_T_arg_t; 在你班级的私人部分,然后这样说: int operator()(const base_T_arg_t &l ...
  • 除了以下划线开头的名称,正如人们在评论中指出的那样,您的问题似乎在行return *((PriorityPair)(*queueArray[0]))._Object 。 让我们从内到外一块一块地看着它,然后一直在努力。 queueArray是PriorityPair** ,在PriorityQueue声明。 这可以被解读为“指向PriorityPair指针”,但在你的情况下,它看起来像是指“指向PriorityPair的指针的原始数组”,这也是一个有效的读数。 到现在为止还挺好。 q ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)