Re: TypeError: Cannot call delete() after .distinct() in the Admin

2022-04-07 Thread Mike Dewhirst

Sorry - just found it in the docs

M

On 7/04/2022 5:05 pm, Mike Dewhirst wrote:

How can I remove the 'Delete' option from Django Admin actions?

Many thanks

Mike




--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/caa68eb7-f56c-4ca9-36c8-86ccf8c17f91%40dewhirst.com.au.


OpenPGP_signature
Description: OpenPGP digital signature


TypeError: Cannot call delete() after .distinct() in the Admin

2022-04-07 Thread Mike Dewhirst

How can I remove the 'Delete' option from Django Admin actions?

Many thanks

Mike

--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d51ac9f7-a46b-61ed-1406-184c5e95b108%40dewhirst.com.au.


OpenPGP_signature
Description: OpenPGP digital signature


Tweak admin 'Action' to avoid Cannot call delete() after .distinct()

2022-03-20 Thread Mike Dewhirst
I am using tweaked querysets to populate the Admin and fully understand 
why this error occurs.


I am using Actions to perform bulk operations on selected records so I 
do need the Action selector widget.


How can I remove the 'Delete selected...' option?

Thanks

Mike


 TypeError at /admin/chemical/chemical/

Cannot call delete() after .distinct().

Request Method: POST
Request URL:http://localhost:8088/admin/chemical/chemical/
Django Version: 3.2.12
Exception Type: TypeError
Exception Value:

Cannot call delete() after .distinct().

Exception Location: 
D:\Users\mike\envs\xxai\lib\site-packages\django\db\models\query.py, 
line 728, in delete

Python Executable:  D:\Users\mike\envs\xxai\Scripts\python.exe
Python Version: 3.8.3
Python Path:

['/var/www/aicis',
 'D:\\Users\\mike\\envs\\xxai\\aicis',
 'C:\\Python38\\python38.zip',
 'C:\\Python38\\DLLs',
 'C:\\Python38\\lib',
 'C:\\Python38',
 'D:\\Users\\mike\\envs\\xxai',
 'D:\\Users\\mike\\envs\\xxai\\lib\\site-packages']

--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c3867097-88c4-3588-9134-4d2302debf43%40dewhirst.com.au.


OpenPGP_signature
Description: OpenPGP digital signature


Re: cannot get value(foreign key) after using distinct()

2021-10-18 Thread Lalit Suthar
since you are using .first() in the query, it will return only 1 object so
I don't think using a for loop our 'category' in template will work

On Mon, 18 Oct 2021 at 18:04, Katharine Wong 
wrote:

> Hi all,
>
> There is a question when I use distinct().
> When I try to use the ORM(distinct & value), I cannot get the value of the
> attribute(foreign key).
>
> models.py
>
>  class Category(models.Model):
>  category = models.CharField(max_length=20)
>
> class Article(models.Model):
>  category = models.ForeignKey(Category, on_delete=models.CASCADE)
>
>
> views.py
>   category =
> Article.objects.filter(visible=True).values('category').distinct().first()
>   return_result.update({'category': category})
>
> template/xxx.html
>
>  {% if category %}
>  {% for name in category %}
> {{ name.category }}
> ...
>
> the result is 4. (int) and there is no result if I type {{
> name.category.category }}
>
> I hope the result is Work which is the 4(category_id) refs.
>
> Thanks,
> Kath
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CALUcQhHOQ7rcg_xLgJocyubWCN8pFOLmvrsnDqbkSWAWF-_Y2A%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CALUcQhHOQ7rcg_xLgJocyubWCN8pFOLmvrsnDqbkSWAWF-_Y2A%40mail.gmail.com?utm_medium=email_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAGp2JVEG%2Bk8fnseW4Tr_iME-dN_%3DTbojM%2BnL5kcwzFgyUdbjtQ%40mail.gmail.com.


cannot get value(foreign key) after using distinct()

2021-10-18 Thread Katharine Wong
Hi all,

There is a question when I use distinct().
When I try to use the ORM(distinct & value), I cannot get the value of the
attribute(foreign key).

models.py

 class Category(models.Model):
 category = models.CharField(max_length=20)

class Article(models.Model):
 category = models.ForeignKey(Category, on_delete=models.CASCADE)


views.py
  category =
Article.objects.filter(visible=True).values('category').distinct().first()
  return_result.update({'category': category})

template/xxx.html

 {% if category %}
 {% for name in category %}
{{ name.category }}
...

the result is 4. (int) and there is no result if I type {{
name.category.category }}

I hope the result is Work which is the 4(category_id) refs.

Thanks,
Kath

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CALUcQhHOQ7rcg_xLgJocyubWCN8pFOLmvrsnDqbkSWAWF-_Y2A%40mail.gmail.com.


Re: Admin TypeError - Cannot call delete() after .distinct()

2021-07-02 Thread Mike Dewhirst
Just looked at that ticket and it seems probable that is what is happening.I'll 
be patient. Thanks for thatM--(Unsigned mail from my phone)
 Original message From: Jason  Date: 
2/7/21  22:30  (GMT+10:00) To: Django users  
Subject: Re: Admin TypeError - Cannot call delete() after .distinct() 
https://code.djangoproject.com/ticket/32682 might be the root cause, which was 
fixed end of April and part of the 3.2.1 release, doesn't seem like its been 
backported to 3.1On Friday, July 2, 2021 at 2:03:28 AM UTC-4 Mike Dewhirst 
wrote:Trying to delete a record in the Admin list view by checking the 
checkbox and selecting the delete action and clicking [Go] the following 
500 error happened.

It seems to be all within the Admin so I'm not sure how to proceed from 
here.

Thanks for any hints

Mike

Traceback (most recent call last):
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\handlers\exception.py", 
line 47, in inner
     response = get_response(request)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\handlers\base.py", 
line 181, in _get_response
     response = wrapped_callback(request, *callback_args, **callback_kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 616, in wrapper
     return self.admin_site.admin_view(view)(*args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
line 130, in _wrapped_view
     response = view_func(request, *args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\views\decorators\cache.py", 
line 44, in _wrapped_view_func
     response = view_func(request, *args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\sites.py", 
line 232, in inner
     return view(request, *args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
line 43, in _wrapper
     return bound_method(*args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
line 130, in _wrapped_view
     response = view_func(request, *args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 1739, in changelist_view
     response = self.response_action(request, 
queryset=cl.get_queryset(request))
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 1408, in response_action
     response = func(self, request, queryset)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\actions.py", 
line 45, in delete_selected
     modeladmin.delete_queryset(request, queryset)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 1109, in delete_queryset
     queryset.delete()
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\db\models\query.py", 
line 728, in delete
     raise TypeError('Cannot call delete() after .distinct().')

Exception Type: TypeError at /admin/chemical/chemical/
Exception Value: Cannot call delete() after .distinct().

-- 
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.






-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/086bef60-4422-4021-949b-84e19e9768b2n%40googlegroups.com.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/60df20c4.1c69fb81.ed7bc.5675SMTPIN_ADDED_MISSING%40gmr-mx.google.com.


Re: Admin TypeError - Cannot call delete() after .distinct()

2021-07-02 Thread Mike Dewhirst
Should have mentioned - I'm running 3.2.4M--(Unsigned mail from my phone)
 Original message From: Jason  Date: 
2/7/21  22:30  (GMT+10:00) To: Django users  
Subject: Re: Admin TypeError - Cannot call delete() after .distinct() 
https://code.djangoproject.com/ticket/32682 might be the root cause, which was 
fixed end of April and part of the 3.2.1 release, doesn't seem like its been 
backported to 3.1On Friday, July 2, 2021 at 2:03:28 AM UTC-4 Mike Dewhirst 
wrote:Trying to delete a record in the Admin list view by checking the 
checkbox and selecting the delete action and clicking [Go] the following 
500 error happened.

It seems to be all within the Admin so I'm not sure how to proceed from 
here.

Thanks for any hints

Mike

Traceback (most recent call last):
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\handlers\exception.py", 
line 47, in inner
     response = get_response(request)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\handlers\base.py", 
line 181, in _get_response
     response = wrapped_callback(request, *callback_args, **callback_kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 616, in wrapper
     return self.admin_site.admin_view(view)(*args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
line 130, in _wrapped_view
     response = view_func(request, *args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\views\decorators\cache.py", 
line 44, in _wrapped_view_func
     response = view_func(request, *args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\sites.py", 
line 232, in inner
     return view(request, *args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
line 43, in _wrapper
     return bound_method(*args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
line 130, in _wrapped_view
     response = view_func(request, *args, **kwargs)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 1739, in changelist_view
     response = self.response_action(request, 
queryset=cl.get_queryset(request))
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 1408, in response_action
     response = func(self, request, queryset)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\actions.py", 
line 45, in delete_selected
     modeladmin.delete_queryset(request, queryset)
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 1109, in delete_queryset
     queryset.delete()
   File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\db\models\query.py", 
line 728, in delete
     raise TypeError('Cannot call delete() after .distinct().')

Exception Type: TypeError at /admin/chemical/chemical/
Exception Value: Cannot call delete() after .distinct().

-- 
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.






-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/086bef60-4422-4021-949b-84e19e9768b2n%40googlegroups.com.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/60df1f7f.1c69fb81.1daca.33a9SMTPIN_ADDED_MISSING%40gmr-mx.google.com.


Re: Admin TypeError - Cannot call delete() after .distinct()

2021-07-02 Thread Sebastian Jung
Hello Mike,

i don't understand why you want make a delete from a distict... Then you
delete random entrys. When you want do delete dupletes then this is a wrong
method to delete dupletes...

Regards

Am Fr., 2. Juli 2021 um 08:03 Uhr schrieb Mike Dewhirst <
mi...@dewhirst.com.au>:

> Trying to delete a record in the Admin list view by checking the
> checkbox and selecting the delete action and clicking [Go] the following
> 500 error happened.
>
> It seems to be all within the Admin so I'm not sure how to proceed from
> here.
>
> Thanks for any hints
>
> Mike
>
> Traceback (most recent call last):
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\core\handlers\exception.py",
>
> line 47, in inner
>  response = get_response(request)
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\core\handlers\base.py",
> line 181, in _get_response
>  response = wrapped_callback(request, *callback_args,
> **callback_kwargs)
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py",
>
> line 616, in wrapper
>  return self.admin_site.admin_view(view)(*args, **kwargs)
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py",
> line 130, in _wrapped_view
>  response = view_func(request, *args, **kwargs)
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\views\decorators\cache.py",
>
> line 44, in _wrapped_view_func
>  response = view_func(request, *args, **kwargs)
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\sites.py",
> line 232, in inner
>  return view(request, *args, **kwargs)
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py",
> line 43, in _wrapper
>  return bound_method(*args, **kwargs)
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py",
> line 130, in _wrapped_view
>  response = view_func(request, *args, **kwargs)
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py",
>
> line 1739, in changelist_view
>  response = self.response_action(request,
> queryset=cl.get_queryset(request))
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py",
>
> line 1408, in response_action
>  response = func(self, request, queryset)
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\actions.py",
>
> line 45, in delete_selected
>  modeladmin.delete_queryset(request, queryset)
>    File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py",
>
> line 1109, in delete_queryset
>  queryset.delete()
>File
> "D:\Users\mike\envs\xxai\lib\site-packages\django\db\models\query.py",
> line 728, in delete
>  raise TypeError('Cannot call delete() after .distinct().')
>
> Exception Type: TypeError at /admin/chemical/chemical/
> Exception Value: Cannot call delete() after .distinct().
>
> --
> Signed email is an absolute defence against phishing. This email has
> been signed with my private key. If you import my public key you can
> automatically decrypt my signature and be sure it came from me. Just
> ask and I'll send it to you. Your email software can handle signing.
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/4ceeffab-480a-aecd-a12d-01f183598d57%40dewhirst.com.au
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAKGT9mzGL34KymQ30B30yn39SY0iDvPvXShoqRvamVyBhqVa%2Bw%40mail.gmail.com.


Re: Admin TypeError - Cannot call delete() after .distinct()

2021-07-02 Thread Jason

https://code.djangoproject.com/ticket/32682 might be the root cause, which 
was fixed end of April and part of the 3.2.1 release, doesn't seem like its 
been backported to 3.1
On Friday, July 2, 2021 at 2:03:28 AM UTC-4 Mike Dewhirst wrote:

> Trying to delete a record in the Admin list view by checking the 
> checkbox and selecting the delete action and clicking [Go] the following 
> 500 error happened.
>
> It seems to be all within the Admin so I'm not sure how to proceed from 
> here.
>
> Thanks for any hints
>
> Mike
>
> Traceback (most recent call last):
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\core\handlers\exception.py",
>  
>
> line 47, in inner
> response = get_response(request)
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\core\handlers\base.py", 
> line 181, in _get_response
> response = wrapped_callback(request, *callback_args, **callback_kwargs)
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
>
> line 616, in wrapper
> return self.admin_site.admin_view(view)(*args, **kwargs)
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
> line 130, in _wrapped_view
> response = view_func(request, *args, **kwargs)
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\views\decorators\cache.py", 
>
> line 44, in _wrapped_view_func
> response = view_func(request, *args, **kwargs)
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\sites.py", 
> line 232, in inner
> return view(request, *args, **kwargs)
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
> line 43, in _wrapper
> return bound_method(*args, **kwargs)
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
> line 130, in _wrapped_view
> response = view_func(request, *args, **kwargs)
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
>
> line 1739, in changelist_view
> response = self.response_action(request, 
> queryset=cl.get_queryset(request))
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
>
> line 1408, in response_action
> response = func(self, request, queryset)
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\actions.py", 
>
> line 45, in delete_selected
> modeladmin.delete_queryset(request, queryset)
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
>
> line 1109, in delete_queryset
> queryset.delete()
>   File 
> "D:\Users\mike\envs\xxai\lib\site-packages\django\db\models\query.py", 
> line 728, in delete
> raise TypeError('Cannot call delete() after .distinct().')
>
> Exception Type: TypeError at /admin/chemical/chemical/
> Exception Value: Cannot call delete() after .distinct().
>
> -- 
> Signed email is an absolute defence against phishing. This email has
> been signed with my private key. If you import my public key you can
> automatically decrypt my signature and be sure it came from me. Just
> ask and I'll send it to you. Your email software can handle signing.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/086bef60-4422-4021-949b-84e19e9768b2n%40googlegroups.com.


Admin TypeError - Cannot call delete() after .distinct()

2021-07-02 Thread Mike Dewhirst
Trying to delete a record in the Admin list view by checking the 
checkbox and selecting the delete action and clicking [Go] the following 
500 error happened.


It seems to be all within the Admin so I'm not sure how to proceed from 
here.


Thanks for any hints

Mike

Traceback (most recent call last):
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\handlers\exception.py", 
line 47, in inner

    response = get_response(request)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\core\handlers\base.py", 
line 181, in _get_response

    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 616, in wrapper

    return self.admin_site.admin_view(view)(*args, **kwargs)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
line 130, in _wrapped_view

    response = view_func(request, *args, **kwargs)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\views\decorators\cache.py", 
line 44, in _wrapped_view_func

    response = view_func(request, *args, **kwargs)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\sites.py", 
line 232, in inner

    return view(request, *args, **kwargs)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
line 43, in _wrapper

    return bound_method(*args, **kwargs)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\utils\decorators.py", 
line 130, in _wrapped_view

    response = view_func(request, *args, **kwargs)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 1739, in changelist_view
    response = self.response_action(request, 
queryset=cl.get_queryset(request))
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 1408, in response_action

    response = func(self, request, queryset)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\actions.py", 
line 45, in delete_selected

    modeladmin.delete_queryset(request, queryset)
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py", 
line 1109, in delete_queryset

    queryset.delete()
  File 
"D:\Users\mike\envs\xxai\lib\site-packages\django\db\models\query.py", 
line 728, in delete

    raise TypeError('Cannot call delete() after .distinct().')

Exception Type: TypeError at /admin/chemical/chemical/
Exception Value: Cannot call delete() after .distinct().

--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.


--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4ceeffab-480a-aecd-a12d-01f183598d57%40dewhirst.com.au.


OpenPGP_signature
Description: OpenPGP digital signature


How to use filtering data while using distinct method in django?

2020-01-16 Thread kaito
please visit this site for more 
info 
https://stackoverflow.com/questions/59764028/how-to-use-filtering-data-while-using-distinct-method-in-django

I hope my title is enough to understand what I mean, please help me on this 
problem guys.

[image: data.PNG]


When I tried this:

   "" id_list = 
grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct()
 
""


I use `distinct()` to eliminates duplicate rows of Students Enrollment 
Record from the query results but I wonder why the result is like this:

[image: badresult.PNG]




What should I do to show the Students name not that QuerySet in my html?

This is my current **views.py**:

id_list = 
grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct()
print(id_list)
grades = 
grade.objects.filter(Students_Enrollment_Records_id__in=id_list)
print(grades)

This is my **models.py**:

class grade(models.Model):
Teacher = models.ForeignKey(EmployeeUser, related_name='+', 
on_delete=models.CASCADE,
null=True, blank=True)
Grading_Categories = models.ForeignKey(gradingCategories, 
related_name='+', on_delete=models.CASCADE,
   null=True, blank=True)
Subjects = models.ForeignKey(Subject, related_name='+', 
on_delete=models.CASCADE, null=True)
Students_Enrollment_Records = 
models.ForeignKey(StudentsEnrolledSubject, related_name='+',

on_delete=models.CASCADE, null=True)
Average = models.FloatField(null=True, blank=True)

**UPDATE**

when I tried this 

piste = 
grade.objects.filter(Teacher_id=m.id).values_list('Students_Enrollment_Records').annotate(Average=Avg('Average')).order_by('Grading_Categories').distinct()

the computation is fix but the teacher name, Subject and Name of students 
didn't display but the ID is display just like this 

[image: result.PNG]

this is my desire answer 

[image: desireanswer.png]




-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/fd4ff945-0793-46e7-aae4-caae652e62ed%40googlegroups.com.


Aggregating distinct across OneToMany relationships using ORM

2020-01-05 Thread 'Stephen' via Django users
Hi all,

I have two Django models; MonitoringPeriod and AssignmentPeriod. Both models 
have start_date and end_date fields. A MonitoringPeriod can be covered by one 
or more AssignmentPeriod instances, which may or may not cover the entire range 
defined by the start and end of the MonitoringPeriod, and may or may not 
overlap. A MonitoringPeriod would be classed as "fully covered" if all distinct 
dates between its start_date and end_date are included in the set of dates 
specified by its related AssignmentPeriods.This is somewhat trivial to define 
in raw SQL but I'd prefer to do it in the ORM query setting - any ideas?

More details and class definitions, as well as raw SQL are available here:
 
https://stackoverflow.com/questions/59478515/aggregating-of-distinct-dates-across-onetomany-relationships-using-djangos-or

Many thanks in advance for any guidance!

S

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/l5HbPZmIugAMG3QraBmb9PHksYYZSlLDinyBzm0MBXVrIpYUUSNdaYijrbSICV6v-_pT4vhO73hEXF_SBrad48x3BfItZZ0z2BFqLeL6Xow%3D%40pm.me.


Re: NotImplemented error combining distinct with annotate

2019-07-22 Thread John Gateley
Thank you Simon, that worked. -- John

On Sun, Jul 21, 2019 at 8:55 PM Simon Charette  wrote:

> Assuming you have a model definition `Salesperson` you could use
>
> Salesperson.object.annotate(
> sales_amount=Sum('sales__sales_amount'),
> )
>
> But given you mentioned 'salesperson' is a text field you can do
>
> persons = Sales.objects.values('salesperson').annotate(
> sum_sales_amount=Sum('sales_amount')
> )
> for person in persons:
> print('Salesperson %s sold %d dollars' % (person['salesperson'],
> person['sum_sales_amount'])
>
> Note that .values() before annotating a an aggregation function results in
> a GROUP BY
> which should should prefer over using DISTINCT.
>
> Cheers,
> Simon
>
> Le dimanche 21 juillet 2019 21:20:37 UTC-4, John Gateley a écrit :
>>
>> Hello,
>>
>> Python version: Python 3.7.2
>> Django version: 2.2.3
>>
>> I want to combine distinct and annotate(Sum(...)), and get the following
>> error:
>> NotImplementedError: annotate() + distinct(fields) is not implemented.
>>
>> To describe: I have a bunch of sales entries like:
>> 'John', 100
>> 'Sam', 50
>> 'John', 200
>> (the model is a text field for salesperson and an integer field for
>> sales_amount)
>>
>> I want to write a query like:
>> res = Sales.objects.distinct('salesperson').annotate(Sum('sales_amount'))
>> for person in res:
>> print('Salesperson %s sold %d dollars' % (person.salesperson,
>> person.sales_amount__count))
>>
>> I would expect:
>> Salesperson John sold 300 dollars
>> Salesperson Sam sold 50 dollars
>>
>> Instead it generates the above error. Is there a way to do this?
>>
>> Thank you,
>>
>> John
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/1f28638f-d43e-41d9-ba43-663d9d05df09%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/1f28638f-d43e-41d9-ba43-663d9d05df09%40googlegroups.com?utm_medium=email_source=footer>
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CABMyA2MfkzCtw66w5y3B768Xt9wC1wcn%3DA1znz-%3D61NKrLbzHA%40mail.gmail.com.


Re: NotImplemented error combining distinct with annotate

2019-07-21 Thread Simon Charette
Assuming you have a model definition `Salesperson` you could use

Salesperson.object.annotate(
sales_amount=Sum('sales__sales_amount'),
)

But given you mentioned 'salesperson' is a text field you can do

persons = Sales.objects.values('salesperson').annotate(
sum_sales_amount=Sum('sales_amount')
)
for person in persons:
print('Salesperson %s sold %d dollars' % (person['salesperson'], 
person['sum_sales_amount'])

Note that .values() before annotating a an aggregation function results in 
a GROUP BY
which should should prefer over using DISTINCT.

Cheers,
Simon

Le dimanche 21 juillet 2019 21:20:37 UTC-4, John Gateley a écrit :
>
> Hello,
>
> Python version: Python 3.7.2
> Django version: 2.2.3
>
> I want to combine distinct and annotate(Sum(...)), and get the following 
> error:
> NotImplementedError: annotate() + distinct(fields) is not implemented.
>
> To describe: I have a bunch of sales entries like:
> 'John', 100
> 'Sam', 50
> 'John', 200
> (the model is a text field for salesperson and an integer field for 
> sales_amount)
>
> I want to write a query like:
> res = Sales.objects.distinct('salesperson').annotate(Sum('sales_amount'))
> for person in res:
> print('Salesperson %s sold %d dollars' % (person.salesperson, 
> person.sales_amount__count))
>
> I would expect:
> Salesperson John sold 300 dollars
> Salesperson Sam sold 50 dollars
>
> Instead it generates the above error. Is there a way to do this?
>
> Thank you,
>
> John
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1f28638f-d43e-41d9-ba43-663d9d05df09%40googlegroups.com.


NotImplemented error combining distinct with annotate

2019-07-21 Thread John Gateley
Hello,

Python version: Python 3.7.2
Django version: 2.2.3

I want to combine distinct and annotate(Sum(...)), and get the following
error:
NotImplementedError: annotate() + distinct(fields) is not implemented.

To describe: I have a bunch of sales entries like:
'John', 100
'Sam', 50
'John', 200
(the model is a text field for salesperson and an integer field for
sales_amount)

I want to write a query like:
res = Sales.objects.distinct('salesperson').annotate(Sum('sales_amount'))
for person in res:
print('Salesperson %s sold %d dollars' % (person.salesperson,
person.sales_amount__count))

I would expect:
Salesperson John sold 300 dollars
Salesperson Sam sold 50 dollars

Instead it generates the above error. Is there a way to do this?

Thank you,

John

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CABMyA2MVHvD5ARbw2UGyikkeJsgLDGbsXkBkGRdx-Bd0UbeSeA%40mail.gmail.com.


Django - How to have multiple (4) distinct forms in CBV

2016-12-09 Thread Leo Shao


I need 4 forms to: sign up for an event (1), un-sign up for an event (2), 
type in a passcode to manage an event (3) which then shows a modal box that 
allows that person to check in everyone that shows up at the event (4). I'm 
using a (ListView, FormView) to allow looping through the numerous events, 
each of which has a form on it (but it's the same class of form that's used 
for signing up).

My current CBV:

class EventsDisplay(ListView, FormView):
template_name='events/index.html'
context_object_name = "events_list"
queryset = Events.objects.all().order_by("date")
form_class = SignUpForm
success_url = "/events/success"

def get_context_data(self, **kwargs):
self.object_list = self.get_queryset()
context = super(EventsDisplay, self).get_context_data(**kwargs)
context['announcement'] = 
Announcement.objects.all().order_by("-datetime")
context['signup'] = SignUps.objects.all().order_by("fullname")
return context

def form_valid(self, form):
instance = form.save(commit=False)
instance.ip = get_ip(self.request)
instance.save()
return super(EventsDisplay, self).form_valid(form)

How would I modify this to support up to 4 different classes of forms.


I'll provided screenshots of my website to better clarify what I want to do:

All the events are displayed on one page, each event has a sign up form 
(with a hidden input containing the {{ events.name }}: 
https://i.gyazo.com/d8da1b0aefb9093b6b63a7f2da0bf428.png

Clicking on OCC Check-Ins, a modal shows up where a passcode is needed to 
access the check-ins: 
https://i.gyazo.com/998330055f27feedb12491d6fd0ac60c.png

Not yet made, but after the passcode is validated for the given event, 
another modal appears where the person can check in people at the event, so 
I'll need a form there.

Clicking on the down arrow brings up a modal that allows users to remove 
themselves (unsign up): 
https://i.gyazo.com/71c8598f77f79643e3b10a8dd67a733d.png I'm using a form 
to POST the {{ events.name }} (hidden input) and the {{ signups.fullname}} 
(hidden 
input) to .delete() the sign up/object.


If it's not possible to do this, will it work if I only have 2 distinct 
forms?

If you would like any additional information/code/clarification, I will 
gladly post them.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/11378ba0-7beb-44d8-8dfd-fc2cf14096a7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django ORM Interaction between order_by(), distinct(), and filter()

2015-06-01 Thread Suriya Subramanian
I found a way to express the second query in the ORM.

Person.objects.filter(sex='F', pk__in=tallest_people)
Thanks,
Suriya

On Monday, June 1, 2015 at 12:13:49 PM UTC+5:30, Suriya Subramanian wrote:
>
> I have a question about how order_by(), distinct(), and filter() interact. 
> This question is applicable only to the PostgreSQL backend since the 
> Queryset is constructed by passing filed arguments to distinct(). 
> https://docs.djangoproject.com/en/1.8/ref/models/querysets/#distinct In 
> the other backends, distinct() accepts no arguments.
>
> I'll illustrate my question with an example model. Here's a link to the 
> code snippet: https://gist.github.com/anonymous/4111b718dbef264fb339
>
> from django.db import models
>  
> class Person(models.Model):
> SEX_CHOICES = (
> ('M', 'Male'),
> ('F', 'Female'),
> )
> name = models.CharField(max_length=255)
> sex = models.CharField(max_length=255, choices=SEX_CHOICES)
> city = models.CharField(max_length=255)
> height = models.DecimalField(max_digits=10, decimal_places=2)
>  
> def __unicode__(self):
> return self.name
>
>
> I am interested in queries about the tallest person in a city. 
> Specifically, 1) the tallest female in each city, and 2) the tallest person 
> in cities where a female is the tallest. I am able to write the first query 
> using the ORM, but not the second query.
>
> import django
> django.setup()
>  
> from testapp.models import Person
>  
> # Get a list consisting of the tallest female in each city.
> tallest_females = Person.objects.filter(sex='F').order_by('city', 
> '-height').distinct('city').values_list('pk', flat=True)
> print tallest_females.query
> # This outputs:
> #
> # SELECT DISTINCT ON ("testapp_person"."city") "testapp_person"."id"
> # FROM "testapp_person"
> # WHERE "testapp_person"."sex" = F
> # ORDER BY "testapp_person"."city" ASC, "testapp_person"."height" DESC
>  
> # Get a list consiting of females who are the tallest (among all people) in
> # their respective cities.
> # How do I get this list using the ORM? Note that I am having resort to
> # filtering results in Python.
> tallest_people = Person.objects.order_by('city', 
> '-height').distinct('city').values_list('pk', flat=True)
> females_who_are_tallest_in_their_city = [ p for p in tallest_people if (p in 
> tallest_females) ]
>  
> # Ideally, I'd like to write:
> # Person.objects.order_by('city', 
> '-height').distinct('city').filter(sex='F').values_list('pk', flat=True)
>
>
> What's a way to compute the results of the second query fully in the 
> database, without resorting to Python code?
>
> Thanks,
> Suriya
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/43f9e3a1-4211-4bfa-aa8d-292cfe436169%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Django ORM Interaction between order_by(), distinct(), and filter()

2015-06-01 Thread Suriya Subramanian
I have a question about how order_by(), distinct(), and filter() interact. 
This question is applicable only to the PostgreSQL backend since the 
Queryset is constructed by passing filed arguments to 
distinct(). 
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#distinct 
In the other backends, distinct() accepts no arguments.

I'll illustrate my question with an example model. Here's a link to the 
code snippet: https://gist.github.com/anonymous/4111b718dbef264fb339

from django.db import models
 
class Person(models.Model):
SEX_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
name = models.CharField(max_length=255)
sex = models.CharField(max_length=255, choices=SEX_CHOICES)
city = models.CharField(max_length=255)
height = models.DecimalField(max_digits=10, decimal_places=2)
 
def __unicode__(self):
return self.name


I am interested in queries about the tallest person in a city. 
Specifically, 1) the tallest female in each city, and 2) the tallest person 
in cities where a female is the tallest. I am able to write the first query 
using the ORM, but not the second query.

import django
django.setup()
 
from testapp.models import Person
 
# Get a list consisting of the tallest female in each city.
tallest_females = Person.objects.filter(sex='F').order_by('city', 
'-height').distinct('city').values_list('pk', flat=True)
print tallest_females.query
# This outputs:
#
# SELECT DISTINCT ON ("testapp_person"."city") "testapp_person"."id"
# FROM "testapp_person"
# WHERE "testapp_person"."sex" = F
# ORDER BY "testapp_person"."city" ASC, "testapp_person"."height" DESC
 
# Get a list consiting of females who are the tallest (among all people) in
# their respective cities.
# How do I get this list using the ORM? Note that I am having resort to
# filtering results in Python.
tallest_people = Person.objects.order_by('city', 
'-height').distinct('city').values_list('pk', flat=True)
females_who_are_tallest_in_their_city = [ p for p in tallest_people if (p in 
tallest_females) ]
 
# Ideally, I'd like to write:
# Person.objects.order_by('city', 
'-height').distinct('city').filter(sex='F').values_list('pk', flat=True)


What's a way to compute the results of the second query fully in the 
database, without resorting to Python code?

Thanks,
Suriya

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/844b90e2-d312-48b9-8239-150ae821d3e3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: .get() has unexpected behaviour on a queryset after previously applying .order_by().distinct()

2015-04-18 Thread Sergiy Khohlov
Both methods use SQL request s.  Try to test using SQL directly. Database
has no idea about a returning order. Good result for filter is "nice shot".
Adding and deleting objects you broke filter method.
Use always order_by for this kind of purpose.
15 квіт. 2015 19:46, користувач "Nick Smith" <ni...@torchbox.com> написав:

> >>> from django.db.models import models
> >>> class MarketPrice(models.Model):
> market = models.CharField(max_length=30)
> crop = models.CharField(max_length=30)
> price = models.PositiveSmallIntegerField()
> date = models.DateField()
>
> def __str__(self):
> return "{}, {}, {}, {}".format(
> self.market,
> self.crop,
> self,price,
> self.date
> )
>
> >>> FIXTURES = [
> ('London', 'carrots', 15, datetime.date(2015, 1, 1)),
> ('London', 'carrots', 20, datetime.date(2015, 1, 2)),
>
> ('London', 'potatoes', 12, datetime.date(2015, 1, 1)),
> ('London', 'potatoes', 14, datetime.date(2015, 1, 2)),
>
> ('Manchester', 'carrots', 18, datetime.date(2015, 1, 1)),
> ('Manchester', 'carrots', 21, datetime.date(2015, 1, 2)),
>
> ('Manchester', 'potatoes', 10, datetime.date(2015, 1, 1)),
> ('Manchester', 'potatoes', 12, datetime.date(2015, 1, 2)),
> ]
>
> >>> for market, crop, price, date in FIXTURES:
> MarketPrice.objects.create(market=market,
>crop=crop,
>price=price,
>date=date)
>
> We want to get only the latest prices for every possible combination of
> markets and crops...
>
> >>> prices = (MarketPrice.objects
>   .order_by('market', 'commodity', '-date')
>   .distinct('market', 'commodity'))
> [,  potatoes, 14, 2015-01-02>,  02>, ]
>
> .filter() works as expected
>
> >>> prices.filter(market='Manchester', crop='carrots')
> []
>
> but .get is totally unexpected
>
> >>> prices.get(market='Manchester', crop='carrots')
> 
>
> not only does it return the 'wrong' entry, but one which didn't even seem
> to be in prices (because it's a distinct queryset)
>
> It looks and feels even weirder if you apply the filtering first:
>
> >>> prices = (MarketPrice.objects
>   .filter(market='Manchester', crop='carrots')
>   .order_by('market', 'commodity', '-date')
>   .distinct('market', 'commodity'))
> >>> prices
> []
>
> >>> prices.get(market='Manchester', crop='carrots')
> 
>
> There's a note seemingly related to this at
> https://docs.djangoproject.com/en/1.7/ref/models/querysets/#django.db.models.query.QuerySet.distinct,
> but I'm not clear how it directly describes what I'm seeing here.
>
> The line which seems to be causing this is from
> https://github.com/django/django/commit/e4757ec7afd54861e0c34d9b0f5edbbac4e2b860,
> which strips the ordering I've previously applied
>
> >>> prices
> []
>
> >>> prices.order_by()
> []
>
> Is this intended behaviour?
>
> PS the above code examples are untested, manually-typed pseudocode for the
> sake of keeping the example simple.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/50f5ba71-bb20-42f4-96bd-3f1ce17338bb%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/50f5ba71-bb20-42f4-96bd-3f1ce17338bb%40googlegroups.com?utm_medium=email_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CADTRxJMpyf2cg2pTMb%3DXiZfLM1dtWT-s3t5__VR6gi4RbjLkJw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


.get() has unexpected behaviour on a queryset after previously applying .order_by().distinct()

2015-04-15 Thread Nick Smith
>>> from django.db.models import models
>>> class MarketPrice(models.Model):
market = models.CharField(max_length=30)
crop = models.CharField(max_length=30)
price = models.PositiveSmallIntegerField()
date = models.DateField()

def __str__(self):
return "{}, {}, {}, {}".format(
self.market,
self.crop,
self,price,
self.date
)

>>> FIXTURES = [
('London', 'carrots', 15, datetime.date(2015, 1, 1)),
('London', 'carrots', 20, datetime.date(2015, 1, 2)),

('London', 'potatoes', 12, datetime.date(2015, 1, 1)),
('London', 'potatoes', 14, datetime.date(2015, 1, 2)),

('Manchester', 'carrots', 18, datetime.date(2015, 1, 1)),
('Manchester', 'carrots', 21, datetime.date(2015, 1, 2)),

('Manchester', 'potatoes', 10, datetime.date(2015, 1, 1)),
('Manchester', 'potatoes', 12, datetime.date(2015, 1, 2)),
]

>>> for market, crop, price, date in FIXTURES:
MarketPrice.objects.create(market=market,
   crop=crop,
   price=price,
   date=date)

We want to get only the latest prices for every possible combination of 
markets and crops...

>>> prices = (MarketPrice.objects
  .order_by('market', 'commodity', '-date')
  .distinct('market', 'commodity'))
[, , , ]

.filter() works as expected

>>> prices.filter(market='Manchester', crop='carrots')
[]

but .get is totally unexpected

>>> prices.get(market='Manchester', crop='carrots')


not only does it return the 'wrong' entry, but one which didn't even seem 
to be in prices (because it's a distinct queryset)

It looks and feels even weirder if you apply the filtering first:

>>> prices = (MarketPrice.objects
  .filter(market='Manchester', crop='carrots')
  .order_by('market', 'commodity', '-date')
  .distinct('market', 'commodity'))
>>> prices
[]

>>> prices.get(market='Manchester', crop='carrots')


There's a note seemingly related to this at 
https://docs.djangoproject.com/en/1.7/ref/models/querysets/#django.db.models.query.QuerySet.distinct,
 
but I'm not clear how it directly describes what I'm seeing here.

The line which seems to be causing this is from 
https://github.com/django/django/commit/e4757ec7afd54861e0c34d9b0f5edbbac4e2b860,
 
which strips the ordering I've previously applied

>>> prices
[]

>>> prices.order_by()
[]

Is this intended behaviour?

PS the above code examples are untested, manually-typed pseudocode for the 
sake of keeping the example simple.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/50f5ba71-bb20-42f4-96bd-3f1ce17338bb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Queryset .count() breaks when counting distinct values generated by .extra()

2015-01-21 Thread Collin Anderson
Hi,

I don't use extra() a lot, but it could be that count() clears out extra. 
This doesn't exactly answer your question, but you may want to try your 
query on the 1.8 alpha using the new available expressions. You might be 
able to do this without needing extra() at all in 1.8.

Collin

On Sunday, January 18, 2015 at 3:24:49 PM UTC-5, Mattias Linnap wrote:
>
> Hi all,
>
> I think I've found a strange case where QuerySet.count() does not match 
> len(queryset), and the behaviour is certainly unexpected.
> But I'm not sure whether this is a bug, some mistake on my part, or a 
> known limitation of combining .extra(), .distinct() and .count().
> I am aware of the default ordering interfering with .distinct(), and 
> already add .order_by() to get rid of it.
>
> I have a model called RadioSignal, with an integer field "rssi". I'm 
> interested in finding out how many distinct values for "rssi / 10" there 
> are (-10, -20, -30, etc).
>
> Here is a commented "./manage.py shell" record:
>
> >>> RadioSignal.objects.count()
> 523 
> >>> RadioSignal.objects.order_by().values('rssi').distinct().count() 
> 49
> >>> connection.queries[-1]['sql']
> 'SELECT COUNT(DISTINCT "maps_radiosignal"."rssi") FROM "maps_radiosignal"'
>
> Looks okay so far. But I'm interested in each distinct tens of RSSI 
> values, not every single value. I can compute these with .extra():
>
> >>> len(RadioSignal.objects.order_by().extra({'tens': 'rssi / 
> 10'}).values('tens').distinct())
> 6
> >>> RadioSignal.objects.order_by().extra({'tens': 'rssi / 
> 10'}).values('tens').distinct()
> [{'tens': -8}, {'tens': -4}, {'tens': -5}, {'tens': -9}, {'tens': -6}, 
> {'tens': -7}]
> >>> connection.queries[-1]['sql']
> 'SELECT DISTINCT (rssi / 10) AS "tens" FROM "maps_radiosignal" LIMIT 21'
>
> Also looks good so far. But running len() on a queryset is unnecessary if 
> I only need the count.
>
> >>> RadioSignal.objects.order_by().extra({'tens': 'rssi / 
> 10'}).values('tens').distinct().count()
> 523
> >>> connection.queries[-1]['sql']
> 'SELECT COUNT(DISTINCT "maps_radiosignal"."id") FROM "maps_radiosignal"'
>
> Uhoh. Somehow .count() keeps the .distinct() part, but replaces the 
> .extra() and .values() parts with counting primary keys?
>
> I tried it with values('tens'), values_list('tens'), and 
> values_list('tens', flat=True), as well no change.
> So far I've tested Django 1.6 with Python 2.7 and PostgreSQL 9.3, and 
> Django 1.7 with Python 3.4 and PostgreSQL 9.1, all seem to behave the same.
>
> I can work around this, since the possible resulting querysets are pretty 
> small, and evaluating them with len() isn't too slow. But I'm wondering if 
> it's a bug in Django, or something else I've missed?
>
> Mattias
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1b2f6dae-712f-4cb3-b8d3-26560198efaa%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Queryset .count() breaks when counting distinct values generated by .extra()

2015-01-18 Thread Mattias Linnap
Hi all,

I think I've found a strange case where QuerySet.count() does not match 
len(queryset), and the behaviour is certainly unexpected.
But I'm not sure whether this is a bug, some mistake on my part, or a known 
limitation of combining .extra(), .distinct() and .count().
I am aware of the default ordering interfering with .distinct(), and 
already add .order_by() to get rid of it.

I have a model called RadioSignal, with an integer field "rssi". I'm 
interested in finding out how many distinct values for "rssi / 10" there 
are (-10, -20, -30, etc).

Here is a commented "./manage.py shell" record:

>>> RadioSignal.objects.count()
523 
>>> RadioSignal.objects.order_by().values('rssi').distinct().count() 
49
>>> connection.queries[-1]['sql']
'SELECT COUNT(DISTINCT "maps_radiosignal"."rssi") FROM "maps_radiosignal"'

Looks okay so far. But I'm interested in each distinct tens of RSSI values, 
not every single value. I can compute these with .extra():

>>> len(RadioSignal.objects.order_by().extra({'tens': 'rssi / 
10'}).values('tens').distinct())
6
>>> RadioSignal.objects.order_by().extra({'tens': 'rssi / 
10'}).values('tens').distinct()
[{'tens': -8}, {'tens': -4}, {'tens': -5}, {'tens': -9}, {'tens': -6}, 
{'tens': -7}]
>>> connection.queries[-1]['sql']
'SELECT DISTINCT (rssi / 10) AS "tens" FROM "maps_radiosignal" LIMIT 21'

Also looks good so far. But running len() on a queryset is unnecessary if I 
only need the count.

>>> RadioSignal.objects.order_by().extra({'tens': 'rssi / 
10'}).values('tens').distinct().count()
523
>>> connection.queries[-1]['sql']
'SELECT COUNT(DISTINCT "maps_radiosignal"."id") FROM "maps_radiosignal"'

Uhoh. Somehow .count() keeps the .distinct() part, but replaces the 
.extra() and .values() parts with counting primary keys?

I tried it with values('tens'), values_list('tens'), and 
values_list('tens', flat=True), as well no change.
So far I've tested Django 1.6 with Python 2.7 and PostgreSQL 9.3, and 
Django 1.7 with Python 3.4 and PostgreSQL 9.1, all seem to behave the same.

I can work around this, since the possible resulting querysets are pretty 
small, and evaluating them with len() isn't too slow. But I'm wondering if 
it's a bug in Django, or something else I've missed?

Mattias


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/21085de5-a899-437c-b13a-8584104df65f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: distinct().filter() applies filter before distinct

2014-06-11 Thread Derek
It might be worth comparing the SQL that Django generates versus what you 
would write (or want to write) by hand:

MyModel.objects.all().query.sql_with_params()

On Tuesday, 10 June 2014 23:17:30 UTC+2, John Rambo wrote:
>
> This better illustrates what I mean:
>
>
> Example.objects.order_by('a','foreignkey__b').distinct('a').filter(foreignkey__b='something')
>
> On Tuesday, June 10, 2014 4:06:50 PM UTC-5, John Rambo wrote:
>>
>> If we chain a call to filter() after a call to distinct(), the filter is 
>> applied to the query before the distinct. How do I filter the results of a 
>> query *after* applying distinct?
>>
>> Example.objects.order_by('a','b').distinct('a').filter(b='something)
>>
>> The where clause in the SQL resulting from filter() means the filter is 
>> applied to the query before the distinct. I want to filter the queryset 
>> resulting from the distinct.
>>
>> This is probably pretty easy, but I just can't quite figure it out and I 
>> can't find anything on it.
>>
>> Another way to ask the question is how do I return a distinct QuerySet 
>> and then filter it?
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/475bed36-5b8e-4892-8e3b-7023913749cc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: distinct().filter() applies filter before distinct

2014-06-10 Thread John Rambo
This better illustrates what I mean:

Example.objects.order_by('a','foreignkey__b').distinct('a').filter(foreignkey__b='something')

On Tuesday, June 10, 2014 4:06:50 PM UTC-5, John Rambo wrote:
>
> If we chain a call to filter() after a call to distinct(), the filter is 
> applied to the query before the distinct. How do I filter the results of a 
> query *after* applying distinct?
>
> Example.objects.order_by('a','b').distinct('a').filter(b='something)
>
> The where clause in the SQL resulting from filter() means the filter is 
> applied to the query before the distinct. I want to filter the queryset 
> resulting from the distinct.
>
> This is probably pretty easy, but I just can't quite figure it out and I 
> can't find anything on it.
>
> Another way to ask the question is how do I return a distinct QuerySet and 
> then filter it?
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/0fe9ac9a-60c5-480f-b7d3-0db32b0a0f3f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


distinct().filter() applies filter before distinct

2014-06-10 Thread John Rambo
 

If we chain a call to filter() after a call to distinct(), the filter is 
applied to the query before the distinct. How do I filter the results of a 
query *after* applying distinct?

Example.objects.order_by('a','b').distinct('a').filter(b='something)

The where clause in the SQL resulting from filter() means the filter is 
applied to the query before the distinct. I want to filter the queryset 
resulting from the distinct.

This is probably pretty easy, but I just can't quite figure it out and I 
can't find anything on it.

Another way to ask the question is how do I return a distinct QuerySet and 
then filter it?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/f0e4bccc-2de6-4018-bd48-d3573ad60e6b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: how to get count of each distinct value

2013-11-22 Thread Fatih Tiryakioglu
Thank you.


--

22 Kasım 2013 Cuma 18:07:47 UTC+2 tarihinde larry@gmail.com yazdı:
>
> On Fri, Nov 22, 2013 at 10:44 AM, Fatih Tiryakioglu 
>  > wrote:
>
>> Hi all,
>>
>> How can I get distribution of values in a field? For example, I have the 
>> scores below:
>>
>>  (score)
>> (raw1)1
>> (raw2)1
>> (raw3)3
>> (raw4)4
>> (raw5)4
>> (raw6)5
>> (raw7)8
>> (raw8)8
>> (raw9)9
>> (raw10)10
>>
>> I want to have a result like that: {1: 2}, {3: 1}, {4: 2}, {5: 1}, {8: 
>> 2}, {9: 1}, {10: 1}. So it is {score: count}.
>>
>> How can I evaluate this only one db hit?
>>
>> Thanks all.
>>
>
> In SQL:
>
> SELECT score, COUNT(*) FROM foo GROUP BY score; 
>
> In Django:
>
> from django.db.models import Count
> q = Foo.objects.values('score').annotate(Count('score'))
> for r in q:
> print r, r.score__count
>  

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/95c5956c-7ca3-4930-9ab4-25fa47b8d249%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: how to get count of each distinct value

2013-11-22 Thread Larry Martell
On Fri, Nov 22, 2013 at 10:44 AM, Fatih Tiryakioglu wrote:

> Hi all,
>
> How can I get distribution of values in a field? For example, I have the
> scores below:
>
>  (score)
> (raw1)1
> (raw2)1
> (raw3)3
> (raw4)4
> (raw5)4
> (raw6)5
> (raw7)8
> (raw8)8
> (raw9)9
> (raw10)10
>
> I want to have a result like that: {1: 2}, {3: 1}, {4: 2}, {5: 1}, {8: 2},
> {9: 1}, {10: 1}. So it is {score: count}.
>
> How can I evaluate this only one db hit?
>
> Thanks all.
>

In SQL:

SELECT score, COUNT(*) FROM foo GROUP BY score;

In Django:

from django.db.models import Count
q = Foo.objects.values('score').annotate(Count('score'))
for r in q:
print r, r.score__count

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CACwCsY4nhWaHgENp0Rp%3D%3DVRgXOhE_uFjb_H8AkwkDADuHUHq5g%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


how to get count of each distinct value

2013-11-22 Thread Fatih Tiryakioglu
Hi all,

How can I get distribution of values in a field? For example, I have the 
scores below:

 (score)
(raw1)1
(raw2)1
(raw3)3
(raw4)4
(raw5)4
(raw6)5
(raw7)8
(raw8)8
(raw9)9
(raw10)10

I want to have a result like that: {1: 2}, {3: 1}, {4: 2}, {5: 1}, {8: 2}, 
{9: 1}, {10: 1}. So it is {score: count}.

How can I evaluate this only one db hit?

Thanks all.


--

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/301f4583-892e-4e06-b3a7-983381b95fbd%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


how to make distinct and order_by work together

2013-08-10 Thread doniyor
I am really stuck in this problem for a while. this is really challenging 
for me. .. tough one... 

i have two models. Location and Rate. 

each location has rates, possibly multiple rates.. let me give you my 
models: 

class Location(models.Model):
  name = models.TextField()
  adres = models.TextField()
class Rate(models.Model):
  location = models.ForeignKey(Location,related_name='locations_rate')
  rate = models.IntegerField(max_length=2)

the case is: 

I am trying to write the sort function which is called when user in resultpage 
the result items sorts e.g. by rate. then the results should be sorted 
ascendingly ordered by rate. 

I tried this: 

locations = 
Location.objects.filter(**s_kwargs).order_by('-locations_rate__rate')

but this is giving me duplicate items. then i tried this: locations = 
Location.objects.filter(**s_kwargs).distinct('id').order_by('-locations_rate__rate')

but i am getting error message saying this wont work as i read in every forum. 
what can i do so that i can sort the items ordering by rates and keeping them 
distinct set? 


please help me 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Suggestion for using distinct on django 1.4+ in your unit tests?

2013-03-06 Thread Brad Pitcher
I believe sqlite supports "distinct" just not "distinct on". I have always
managed to find workarounds using "distinct" anywhere I formerly used
"distinct on".
On Mar 6, 2013 7:01 AM, "Toran Billups" <tor...@gmail.com> wrote:

> I recently upgraded to django 1.4 and found that my "distinct" queries
> don't work anymore in my test code because sqlite doesn't support it -how
> is everyone using this for integration testing?
>
> Thank you in advance
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Suggestion for using distinct on django 1.4+ in your unit tests?

2013-03-06 Thread Toran Billups
I recently upgraded to django 1.4 and found that my "distinct" queries 
don't work anymore in my test code because sqlite doesn't support it -how 
is everyone using this for integration testing? 

Thank you in advance

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Need to get a distinct category list from many to many

2013-02-27 Thread frocco
Hello,

I Have a product table that has a many to many relation to a category table.

When I query the products, I want to display a unique list of the 
categories associated with the product query.

product table
product_id
categories = models.ManyToManyField(Category, related_name="cat")

category table
category_id

product_category table
product_id
category_id

I tried this, but it is not working.
c = Product.objects.filter(keywords__contains=search, 
is_active=True).distinct('category_id')

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Distinct Values in ModelChoiceField

2012-08-23 Thread Joseph Mutumi
@Melvyn Thank you. It actually worked out as you said. It needed a redesign.

On Wed, Aug 22, 2012 at 1:44 PM, Sithembewena Lloyd Dube
<zebr...@gmail.com>wrote:

> @Melvyn, thanks - that makes sense.
>
>
> On Wed, Aug 22, 2012 at 3:18 AM, Melvyn Sopacua <m.r.sopa...@gmail.com>wrote:
>
>> On 22-8-2012 3:04, Sithembewena Lloyd Dube wrote:
>>
>> > I found your response to the OP interesting, yet I cannot quite follow
>> it.
>> > Even if he sets a unique attribute (presumably Boolean/ Checkbox?)
>>
>> Nope, this unique attribute:
>> <https://docs.djangoproject.com/en/1.4//ref/models/fields/#unique>
>>
>> By design, the foreign key will now not contain duplicates so distinct
>> is no longer necessary.
>> --
>> Melvyn Sopacua
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To post to this group, send email to django-users@googlegroups.com.
>> To unsubscribe from this group, send email to
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at
>> http://groups.google.com/group/django-users?hl=en.
>>
>>
>
>
> --
> Regards,
> Sithembewena Lloyd Dube
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Distinct Values in ModelChoiceField

2012-08-22 Thread Sithembewena Lloyd Dube
@Melvyn, thanks - that makes sense.

On Wed, Aug 22, 2012 at 3:18 AM, Melvyn Sopacua <m.r.sopa...@gmail.com>wrote:

> On 22-8-2012 3:04, Sithembewena Lloyd Dube wrote:
>
> > I found your response to the OP interesting, yet I cannot quite follow
> it.
> > Even if he sets a unique attribute (presumably Boolean/ Checkbox?)
>
> Nope, this unique attribute:
> <https://docs.djangoproject.com/en/1.4//ref/models/fields/#unique>
>
> By design, the foreign key will now not contain duplicates so distinct
> is no longer necessary.
> --
> Melvyn Sopacua
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Regards,
Sithembewena Lloyd Dube

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Distinct Values in ModelChoiceField

2012-08-21 Thread Melvyn Sopacua
On 22-8-2012 3:04, Sithembewena Lloyd Dube wrote:

> I found your response to the OP interesting, yet I cannot quite follow it.
> Even if he sets a unique attribute (presumably Boolean/ Checkbox?)

Nope, this unique attribute:
<https://docs.djangoproject.com/en/1.4//ref/models/fields/#unique>

By design, the foreign key will now not contain duplicates so distinct
is no longer necessary.
-- 
Melvyn Sopacua

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Distinct Values in ModelChoiceField

2012-08-21 Thread Sithembewena Lloyd Dube
Hi Melvyn,

I found your response to the OP interesting, yet I cannot quite follow it.
Even if he sets a unique attribute (presumably Boolean/ Checkbox?), he
would still need a mechanism to filter the result set at runtime? Please
expound?

On Mon, Aug 20, 2012 at 11:12 AM, Melvyn Sopacua <m.r.sopa...@gmail.com>wrote:

> On 20-8-2012 0:16, Joseph Mutumi wrote:
>
> > That particular field at times appears multiple times in the database.
> How
> > do I make it
> > only have distinct values?
> >
> > This is a snippet, drop down will have repeated values if same color is
> > entered:
> >
> > class FavoriteColor(models.Model):
> > color = models.CharField(max_length=255)
> >
> > def __unicode__(self):
> > return self.color
> You should invest in fixing the flaw in the design. Set the unique
> attribute on the color field after you manually remove all duplicates
> from the database.
>
>
> --
> Melvyn Sopacua
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Regards,
Sithembewena Lloyd Dube

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Distinct Values in ModelChoiceField

2012-08-20 Thread Melvyn Sopacua
On 20-8-2012 0:16, Joseph Mutumi wrote:

> That particular field at times appears multiple times in the database. How
> do I make it
> only have distinct values?
> 
> This is a snippet, drop down will have repeated values if same color is
> entered:
> 
> class FavoriteColor(models.Model):
> color = models.CharField(max_length=255)
> 
> def __unicode__(self):
> return self.color
You should invest in fixing the flaw in the design. Set the unique
attribute on the color field after you manually remove all duplicates
from the database.


-- 
Melvyn Sopacua

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Distinct Values in ModelChoiceField

2012-08-19 Thread Sithembewena Lloyd Dube
I reckon you could try the following:
- declare a function which does a 'select distinct' and returns the
queryset via the ORM
e.g.

def distinct_colors():
results = FavoriteColor.objects.all().values("color").distinct()
return results

then ...

class FavoriteThingsForm(forms.ModelForm):
color = forms.ModelChoiceField(queryset=distinct_colors)

I think that you may have to explicitly declare all your form fields and
get rid of the class Meta declaration. Not verified, so head here for more
information:
https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield


On Mon, Aug 20, 2012 at 12:16 AM, Joseph Mutumi <jjmut...@gmail.com> wrote:

> Hello,
>
> I have a model that has a foreign key field that I want to use in a form
> as a select box.
> That particular field at times appears multiple times in the database. How
> do I make it
> only have distinct values?
>
> This is a snippet, drop down will have repeated values if same color is
> entered:
>
> class FavoriteColor(models.Model):
> color = models.CharField(max_length=255)
>
> def __unicode__(self):
> return self.color
>
> class FavoriteThings(models.Model):
> name = models.CharField(max_length=10)
> color = models.ForeignKey(FavoriteColor)
>
> class FavoriteThingsForm(forms.ModelForm):
> class Meta:
> model = FavoriteThings
>
> Thank you
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>



-- 
Regards,
Sithembewena Lloyd Dube

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Distinct Values in ModelChoiceField

2012-08-19 Thread Joseph Mutumi
Hello,

I have a model that has a foreign key field that I want to use in a form as
a select box.
That particular field at times appears multiple times in the database. How
do I make it
only have distinct values?

This is a snippet, drop down will have repeated values if same color is
entered:

class FavoriteColor(models.Model):
color = models.CharField(max_length=255)

def __unicode__(self):
return self.color

class FavoriteThings(models.Model):
name = models.CharField(max_length=10)
color = models.ForeignKey(FavoriteColor)

class FavoriteThingsForm(forms.ModelForm):
class Meta:
model = FavoriteThings

Thank you

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: DISTINCT ON fields is not supported by this database backend

2012-06-25 Thread Mário Neto
What's your database backend?
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct


Note

This ability to specify field names is only available in PostgreSQL.


[]s

2012/6/24 Marcin Tustin <marcin.tus...@gmail.com>

> DISTINCT ON fields is not supported by this database backend
>
> What more is there to say? Either stop using the distinct method, or switch 
> to another database backend.
>
>
> On Sun, Jun 24, 2012 at 11:24 AM, upmauro <upma...@gmail.com> wrote:
>
>> Please help,
>>
>> http://dpaste.com/762942/
>>
>> Thanks alot !
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msg/django-users/-/v5qIbmtR5ZwJ.
>> To post to this group, send email to django-users@googlegroups.com.
>> To unsubscribe from this group, send email to
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at
>> http://groups.google.com/group/django-users?hl=en.
>>
>
>
>
> --
> Marcin Tustin
> Tel: 07773 787 105
>
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>



-- 
Att. *Mário Araújo Chaves Neto*
*Programmer, Designer and U.I. Engineer*
*
*
*MBA in Design Digital* - 2008 - FIC
*Analysis and Systems Development* - 2011 - Estácio
*D**esign and Implementation of Internet Environments* - 2003 - FIC

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: DISTINCT ON fields is not supported by this database backend

2012-06-24 Thread Marcin Tustin
DISTINCT ON fields is not supported by this database backend

What more is there to say? Either stop using the distinct method, or
switch to another database backend.


On Sun, Jun 24, 2012 at 11:24 AM, upmauro <upma...@gmail.com> wrote:

> Please help,
>
> http://dpaste.com/762942/
>
> Thanks alot !
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/v5qIbmtR5ZwJ.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>



-- 
Marcin Tustin
Tel: 07773 787 105

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



DISTINCT ON fields is not supported by this database backend

2012-06-24 Thread upmauro
Please help,

http://dpaste.com/762942/

Thanks alot !

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/v5qIbmtR5ZwJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Distinct queries and order_by

2012-05-10 Thread David
Hello

With a distinct query I understand the need to make the column that is 
required to be distinct the first column to order by.

eg:

lm = Modification.objects.select_related().distinct('object_id').filter(
content_type=topic_ct
).exclude(action=2).order_by('object_id', '-modified_on')

Having done the above, I need to reorder the resultset by modified_on and 
remove the object_id order. Is this possible? Do I need to take a copy of 
the queryset and order that?

Thank you for any assistance

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/g9J4DZXYj-kJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Using DISTINCT on related model fields

2012-01-10 Thread John
I found a solution from the annotate docs:

A.objects.values('b__name').distinct()

tada!  hope this helps someone else later :)

On Jan 10, 3:43 pm, John <theu...@gmail.com> wrote:
> I'm trying to express this query using the Django ORM:
>
> SELECT DISTINCT test_b.name FROM test_a LEFT JOIN test_b ON
> test_a.b_id = test_b.id
>
> using Django (with models 'A' and 'B') all I seem to be able to get is
>
> SELECT DISTINCT test_a.name, test_a.id FROM a INNER JOIN test_b ON
> test_a.b_id = test_b.id
>
> via the query:
>
> A.objects.all().distinct('b__name')
>
> I've tried various changes, including select_related() to try and
> convince it to follow the relation, but no matter what I do it ends up
> using the fields from the A model in the DISTINCT clause rather than
> B.  I assume that part of the problem is that the query I want to
> express does not return an A object, but I can't think of how to use
> the B model to phrase it in the ORM
> (B.objects.all.distinct('name').filter( "has at least one A
> model" ) ? )

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Using DISTINCT on related model fields

2012-01-10 Thread John
I'm trying to express this query using the Django ORM:

SELECT DISTINCT test_b.name FROM test_a LEFT JOIN test_b ON
test_a.b_id = test_b.id

using Django (with models 'A' and 'B') all I seem to be able to get is

SELECT DISTINCT test_a.name, test_a.id FROM a INNER JOIN test_b ON
test_a.b_id = test_b.id

via the query:

A.objects.all().distinct('b__name')

I've tried various changes, including select_related() to try and
convince it to follow the relation, but no matter what I do it ends up
using the fields from the A model in the DISTINCT clause rather than
B.  I assume that part of the problem is that the query I want to
express does not return an A object, but I can't think of how to use
the B model to phrase it in the ORM
(B.objects.all.distinct('name').filter( "has at least one A
model" ) ? )

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: object value distinct for ForeignKey

2011-07-27 Thread Ian Clelland
On Wed, Jul 27, 2011 at 9:29 AM, Ian Clelland <clell...@gmail.com> wrote:

>
>
> On Mon, Jul 25, 2011 at 11:29 AM, Alfredo Alessandrini <
> alfreal...@gmail.com> wrote:
>
>> Hi,
>>
>> I've a model testDB with a foreignkey "country" related to another
>> database.
>>
>> I need to retrieve the unique value of country.common_name.
>>
>> With this
>>
>> country_list = testDB.objects.values('country').distinct
>>
>> I can retrieve the unique value, but only the ID.
>>
>> In [63]: testDB.objects.values('country').distinct
>> Out[63]: > {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
>> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
>> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
>> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
>> {'country': 0L}, {'country': 0L}, {'country': 0L}, '...(remaining
>> elements truncated)...']>
>>
>> How can I  retrieve the attribute "common_name" of the country object?
>>
>
> The "" is usually a clue that what you have retrieved is
> actually a method, and you haven't called that method yet.
>
> Try:
> testDB.objects.values('country').distinct()
>
> (Although you should probably also read the note here:
> https://docs.djangoproject.com/en/1.3/ref/models/querysets/#distinct to
> see why you might want to  be writing
> testDB.objects.order_by().values('country').distinct() )
>
>

And this time, I'll actually respond after reading the last line of your
question -- if what you want is a list of distinct country *names*, where
the name is a field on the country object, you are looking for somethng like
this:

testDB.objects.order_by().values('country__common_name').distinct()


-- 
Regards,
Ian Clelland
<clell...@gmail.com>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: object value distinct for ForeignKey

2011-07-27 Thread Ian Clelland
On Mon, Jul 25, 2011 at 11:29 AM, Alfredo Alessandrini <alfreal...@gmail.com
> wrote:

> Hi,
>
> I've a model testDB with a foreignkey "country" related to another
> database.
>
> I need to retrieve the unique value of country.common_name.
>
> With this
>
> country_list = testDB.objects.values('country').distinct
>
> I can retrieve the unique value, but only the ID.
>
> In [63]: testDB.objects.values('country').distinct
> Out[63]:  {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
> {'country': 0L}, {'country': 0L}, {'country': 0L}, {'country': 0L},
> {'country': 0L}, {'country': 0L}, {'country': 0L}, '...(remaining
> elements truncated)...']>
>
> How can I  retrieve the attribute "common_name" of the country object?
>

The "" is usually a clue that what you have retrieved is
actually a method, and you haven't called that method yet.

Try:
testDB.objects.values('country').distinct()

(Although you should probably also read the note here:
https://docs.djangoproject.com/en/1.3/ref/models/querysets/#distinct to see
why you might want to  be writing
testDB.objects.order_by().values('country').distinct() )


>
> thanks in advance,
>
> Alfredo
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Regards,
Ian Clelland
<clell...@gmail.com>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



object value distinct for ForeignKey

2011-07-25 Thread Alfredo Alessandrini
Hi,

I've a model testDB with a foreignkey "country" related to another database.

I need to retrieve the unique value of country.common_name.

With this

country_list = testDB.objects.values('country').distinct

I can retrieve the unique value, but only the ID.

In [63]: testDB.objects.values('country').distinct
Out[63]: 

How can I  retrieve the attribute "common_name" of the country object?


thanks in advance,

Alfredo

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Using distinct and ordering

2011-06-24 Thread Chris Matthews
Hi,

I had a problem with using distinct() which was not so distinct. It was because 
I did not specify an order_by() and the underlying ordering column on the model 
was in values().

It also selects my ordering column (SQL needs it for the ordering) and the SQL 
DISTINCT is applied at row level.

It might be unfortunate that Django does not implement distinct(column/s).

Note that Postgres has this constraint: ERROR: SELECT DISTINCT ON expressions 
must match initial ORDER BY expressions.

It would actually be nice if:
  I could select values('town_name', 'province__country__name', 
'province__name').distinct('town_name').
  Then the distinct('town_name') should generate a SQL DISTINCT ON (town_name) 
town_name.
  The generated SQL should also drop the model ordering if the values(column/s) 
and ordering column/s do not match (because of the SQL constraint).

I am not sure if the other databases supports this.

Here is my model & query (we use Postal Code not Zip Code):

class Postal_Code(AbstractCommonAll):
suburb   = models.CharField()
box_code = models.CharField()
street_code  = models.CharField()
town_name= models.CharField()
province = models.ForeignKey(Province)

class Meta:
ordering = ("suburb",)

For brevity I have left out models: Province (which has ForeignKey to Country).

And my statement was:
self.filter(town_name__istartswith='Randfo').values('town_name').distinct() 
- returns multiple rows 'cos it selects suburb for the ordering.


self.filter(town_name__istartswith='Randfo').values('town_name').distinct().order_by('town_name')
 - works 'cos it's the correct way if you use ordering on another column.

self.filter(town_name__istartswith='Randfo').values('town_name').distinct().order_by()
 - this works as I would have expected 'cos it drops the SQL ORDER BY.

So it would be nice to do this:
self.filter(town_name__istartswith='Randfo').values('town_name', 
'province__country__name', 'province__name').distinct('town_name')

Regards

Chris Matthews


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Selecting distinct months from a QuerySet

2011-05-19 Thread Scott Gould
I'd either add a manager with a method that did the query you describe
in SQL, or (if you're wanting the whole queryset anyway) just
calculate it via:

months = list(set(x.datetime_field.month for x in queryset))
months.sort()

On May 19, 1:03 am, Ian Turner <ian.tur...@gmail.com> wrote:
> Hi,
>
> I would like to get a distinct list of months from a datetime field on an
> already defined QuerySet.
>
> SQL that I would use manually to get distinct from all records on the model.
> SELECT DISTINCT MONTH(`some_datetime_field`) as `month` FROM `some_model`
> ORDER BY `month`
>
> I don't need the year so .dates() gives me too much information to loop
> over.  Any ideas?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Selecting distinct months from a QuerySet

2011-05-18 Thread Ian Turner
Hi,

I would like to get a distinct list of months from a datetime field on an 
already defined QuerySet.

SQL that I would use manually to get distinct from all records on the model.
SELECT DISTINCT MONTH(`some_datetime_field`) as `month` FROM `some_model` 
ORDER BY `month`

I don't need the year so .dates() gives me too much information to loop 
over.  Any ideas?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Custom ModelAdmin form for distinct logged users

2011-01-28 Thread Daniel Roseman
On Friday, January 28, 2011 12:22:04 AM UTC, Mario8k wrote:
>
> Hello, 
>
> How can I customize a form by the user who is logged in? 
> For example, if the user is_superuser(), i need to display the 
> standard admin form, but if the user is another one, show only some 
> fields and not all model fields. For this, I coud use 
> ModelAdmin.fields (or exclude, or readonly_fields), but i don't know 
> how to make it conditional to the user. 
>
> Regards, Mario. 
>

Since this is in the admin, there's a hook especially for this 
-  ModelAdmin.get_form(). This is a method that you can override in your own 
ModelAdmin subclass - it's passed the request so you can check the value of 
request.user and return the appropriate form. See the code in 
django.contrib.admin.options.
--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Custom ModelAdmin form for distinct logged users

2011-01-28 Thread Moya, Mario
2011/1/28 hollando 

Hi hollando,

You can use proxy models. Refer to
>
> http://stackoverflow.com/questions/2223375/multiplue-modeladmins-views-for-same-model-in-django-admin
>

I can't set permissions for proxy models, i think because the table
auth_permissions doesn't have the proxy records.
That is, i have the Foo model and the FooProxy. Whe i loggin as superuser i
see both, Foo and FooProxy admin forms. But when i log as other user (supose
proxyuser), who only have the permission "Can change foo", only see Foo
admin forms.

How can i reach the way to login as proxyuser, and enter only to the
FooProxy admin forms?


>
> On 1月27日, 下午4时22分, Mario8k  wrote:
> > Hello,
> >
> > How can I customize a form by the user who is logged in?
> > For example, if the user is_superuser(), i need to display the
> > standard admin form, but if the user is another one, show only some
> > fields and not all model fields. For this, I coud use
> > ModelAdmin.fields (or exclude, or readonly_fields), but i don't know
> > how to make it conditional to the user.
> >
> > Regards, Mario.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Lic. Mario Moya
Tel: +54 299 4771196
Cel: +54 299 155023987
mm...@8ksoft.com.ar
Belgrano 167 - (8324) Cipolletti, Río Negro
http://www.8ksoft.com.ar


*Cuidar el medio ambiente depende de todos, imprime sólo lo necesario.*

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Custom ModelAdmin form for distinct logged users

2011-01-27 Thread hollando
You can use proxy models. Refer to
http://stackoverflow.com/questions/2223375/multiplue-modeladmins-views-for-same-model-in-django-admin

On 1月27日, 下午4时22分, Mario8k  wrote:
> Hello,
>
> How can I customize a form by the user who is logged in?
> For example, if the user is_superuser(), i need to display the
> standard admin form, but if the user is another one, show only some
> fields and not all model fields. For this, I coud use
> ModelAdmin.fields (or exclude, or readonly_fields), but i don't know
> how to make it conditional to the user.
>
> Regards, Mario.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Custom ModelAdmin form for distinct logged users

2011-01-27 Thread Mario8k
Hello,

How can I customize a form by the user who is logged in?
For example, if the user is_superuser(), i need to display the
standard admin form, but if the user is another one, show only some
fields and not all model fields. For this, I coud use
ModelAdmin.fields (or exclude, or readonly_fields), but i don't know
how to make it conditional to the user.

Regards, Mario.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



distinct in autocomplete

2010-10-20 Thread alecx
Hello,

how do I get only distinct values of that query in the autocomplete
field:

def autocomplete_techlastname(request):
if request.GET.has_key('q'):
tags = 
Item.objects.filter(techlastname__icontains=request.GET['q'])
[:5]
return HttpResponse('\n'.join(tag.techlastname for tag in tags))
return HttpResponse()

appending distinct seems not to work.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct doesn't work on admin actions¿?

2010-10-13 Thread Marc Aymerich
On Wed, Oct 13, 2010 at 3:57 AM, Karen Tracey <kmtra...@gmail.com> wrote:

> On Tue, Oct 12, 2010 at 6:31 AM, Marc Aymerich <glicer...@gmail.com>wrote:
>
>> I'm writing an action for the django admin site. My model looks like:
>>
>> class order(models.Model):
>> entity = models.ForeignKey(entity)
>> [...]
>>
>>
>> I select an arbitrary number of orders and I need to know the different
>> entities that they have. It works on shell:
>>
>> >>> queryset = order.objects.all()
>>  >>> queryset.all().values_list('entity', flat=True).distinct()
>> [1L]
>>
>> But on Admin seems the distinct part of the queryset doesn't work
>>
>> class orderAdmin(admin.ModelAdmin):
>>[]
>> def invoice(self, request, queryset):
>> print str(queryset.all().values_list('entity',
>> flat=True).distinct())
>> []
>>
>>
>> Here the output of selecting all order elements(4), the output is a little
>> different from the same operation in shell :(
>>
>> [1L, 1L, 1L, 1L]
>>
>>
>> What's happening here?
>>
>
> Whenever distinct() doesn't seem to work like it should the first thing to
> check is whether an oder_by() specified in the queryset is causing the
> duplicates (see
> http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct).
> Adding order_by() to the queryset you are using will clear any previously
> specified ordering and should eliminate the duplicates (if that is in fact
> what is causing the problem).



Thanks you very much Karen, the problem was this! Now it works as expected
:)  * *


> --

Marc

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct doesn't work on admin actions¿?

2010-10-12 Thread Karen Tracey
On Tue, Oct 12, 2010 at 6:31 AM, Marc Aymerich <glicer...@gmail.com> wrote:

> I'm writing an action for the django admin site. My model looks like:
>
> class order(models.Model):
> entity = models.ForeignKey(entity)
> [...]
>
>
> I select an arbitrary number of orders and I need to know the different
> entities that they have. It works on shell:
>
> >>> queryset = order.objects.all()
>  >>> queryset.all().values_list('entity', flat=True).distinct()
> [1L]
>
> But on Admin seems the distinct part of the queryset doesn't work
>
> class orderAdmin(admin.ModelAdmin):
>[]
> def invoice(self, request, queryset):
> print str(queryset.all().values_list('entity',
> flat=True).distinct())
> []
>
>
> Here the output of selecting all order elements(4), the output is a little
> different from the same operation in shell :(
>
> [1L, 1L, 1L, 1L]
>
>
> What's happening here?
>

Whenever distinct() doesn't seem to work like it should the first thing to
check is whether an oder_by() specified in the queryset is causing the
duplicates (see
http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct). Adding
order_by() to the queryset you are using will clear any previously specified
ordering and should eliminate the duplicates (if that is in fact what is
causing the problem).

Karen
-- 
http://tracey.org/kmt/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



distinct doesn't work on admin actions¿?

2010-10-12 Thread Marc Aymerich
Hi!
I'm writing an action for the django admin site. My model looks like:

class order(models.Model):
entity = models.ForeignKey(entity)
[...]


I select an arbitrary number of orders and I need to know the different
entities that they have. It works on shell:

>>> queryset = order.objects.all()
>>> queryset.all().values_list('entity', flat=True).distinct()
[1L]

But on Admin seems the distinct part of the queryset doesn't work

class orderAdmin(admin.ModelAdmin):
   []
def invoice(self, request, queryset):
print str(queryset.all().values_list('entity',
flat=True).distinct())
[]


Here the output of selecting all order elements(4), the output is a little
different from the same operation in shell :(

[1L, 1L, 1L, 1L]


What's happening here?
Thanks!
-- 
Marc

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Need help selecting a distinct set of values from a queryset

2010-09-19 Thread Uwe Schuerkamp
Sorry to follow up on my own drivel, but I think I've found a solution
in the fine django docs:

obs =
Observation.objects.filter(observer=o.id,location__location_area__area_country__country_abbrev=country_code).values("bird_id").annotate(Count("bird"))

seems to do the job nicely for all combinations of areas, countries
and so on. The key seems to be the usage of the Count() aggregate
function.

Thanks for listening,

Uwe

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Need help selecting a distinct set of values from a queryset

2010-09-19 Thread Uwe Schuerkamp
Hi folks,

some of you may remember I'm working on a site for birders where they
can enter and keep track of their observations of various birds.

Multiple viewings of a species can be entered at different observation
locations, so for the ranking page (which considers only the number of
distinct species), I need to find the set of observed species with
multiple viewing dropped from the set.

I've tried something like this:

birds_observed = {}
for o in observations:
   birds_observed[o.bird.id] = 1

number_of observations = len(birds_observed)

and then repeat that loop for every observer in the database. Using
the excellent debug snippet from djangosnippets.org, I've found this
creates about 3,000  sql queries total on the database of the form

select bird_id from club300_birds where .

for each and every observation in the above set, rinse and repeat for
every observer being ranked.

My question: Is it possible to have Django select the distinct()
bird_ids from a set of observations for a given observer?

I've tried using raw SQL queries, but it feels and looks like a hack
and a definite break of the DRY principle, and usage of the django
distinct() query function sadly eludes me.

Thanks in advance for your comments,

Uwe

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Bug with distinct + aggregate ?

2010-09-14 Thread donato.gr
I managed in this way:
>>> subquery = Father.objects.filter(sons__in=[adam, bernard])
>>> Father.objects.filter(pk__in=subquery).aggregate(Sum('age'))

this gives the correct result.

Is there a better way to do so? (maybe more efficient?)


Thanks


On 13 Set, 17:51, "donato.gr" <donato...@gmail.com> wrote:
> Hi,
> when using 'aggregate(Sum(...))' on a queryset that is also using
> 'distinct()', 'DISTINCT' is misplaced in resulting SQL query...
>
> Here is a silly sample code:
>
> I have the following classes:
> class Son(models.Model):
>         name = models.CharField(max_length=20)
>
>         def __unicode__(self):
>                 return self.name
>
> class Father(models.Model):
>         name = models.CharField(max_length=20)
>         age = models.IntegerField()
>         sons = models.ManyToManyField(Son)
>
>         def __unicode__(self):
>                 return '%s - %s' %(self.name, self.age)
>
> I want to compute the total age of fathers who have a son called Adam
> or Bernard:
>
> so:
>
> >>> f = Father.objects.create(name='Chris', age=30)
> >>> adam = f.sons.create(name='Adam')
> >>> bernard = f.sons.create(name='Bernard')
> >>> f.sons.all() #Check that everything is ok
>
> [, ]
>
> >>> Father.objects.filter(sons__in=[adam, bernard]) #Let's see the fathers 
> >>> that have either Adam or Bernard among their sons
>
> [, ]
>
> >>> Father.objects.filter(sons__in=[adam, bernard]).distinct() #Since Chris 
> >>> have both, he appears twice; so, I have to apply 'distinct'
>
> []
>
> >>> Father.objects.filter(sons__in=[adam, 
> >>> bernard]).distinct().aggregate(Sum('age'))  #Let's see the total age...
>
> {'age__sum': 60}
>
> I think this is an error: the total age should be 30...
>
> The SQL query is:>>> from django.db import connection
> >>> connection.queries[-1]
>
> {'time': '0.000',
> 'sql': u'SELECT DISTINCT SUM(`testing_father`.`age`) AS `age__sum`
> FROM `testing_father` INNER JOIN `testing_father_sons` ON
> (`testing_father`.`id` = `testing_father_sons`.`father_id`) WHERE
> `testing_father_sons`.`son_id` IN (7, 6)'}
>
> So, Django applies DISTINCT on values already summed, while it shouls
> apply DISTINCT BEFORE summing.
>
> What do you think?
>
> Note that my actual problem is that I have to apply aggregation on a
> queryset which is provided by a 'black-box' function: the queryset is
> already provided with the '__in' filter and the 'distinct' clause and
> I cannot change its behaviour, nor taking distinct back...
>
> Any suggestion?
>
> Thanks a lot

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Bug with distinct + aggregate ?

2010-09-13 Thread donato.gr
Hi,
when using 'aggregate(Sum(...))' on a queryset that is also using
'distinct()', 'DISTINCT' is misplaced in resulting SQL query...

Here is a silly sample code:

I have the following classes:
class Son(models.Model):
name = models.CharField(max_length=20)

def __unicode__(self):
return self.name

class Father(models.Model):
name = models.CharField(max_length=20)
age = models.IntegerField()
sons = models.ManyToManyField(Son)

def __unicode__(self):
return '%s - %s' %(self.name, self.age)

I want to compute the total age of fathers who have a son called Adam
or Bernard:

so:

>>> f = Father.objects.create(name='Chris', age=30)
>>> adam = f.sons.create(name='Adam')
>>> bernard = f.sons.create(name='Bernard')
>>> f.sons.all() #Check that everything is ok
[, ]

>>> Father.objects.filter(sons__in=[adam, bernard]) #Let's see the fathers that 
>>> have either Adam or Bernard among their sons
[, ]

>>> Father.objects.filter(sons__in=[adam, bernard]).distinct() #Since Chris 
>>> have both, he appears twice; so, I have to apply 'distinct'
[]

>>> Father.objects.filter(sons__in=[adam, 
>>> bernard]).distinct().aggregate(Sum('age'))  #Let's see the total age...
{'age__sum': 60}

I think this is an error: the total age should be 30...

The SQL query is:
>>> from django.db import connection
>>> connection.queries[-1]
{'time': '0.000',
'sql': u'SELECT DISTINCT SUM(`testing_father`.`age`) AS `age__sum`
FROM `testing_father` INNER JOIN `testing_father_sons` ON
(`testing_father`.`id` = `testing_father_sons`.`father_id`) WHERE
`testing_father_sons`.`son_id` IN (7, 6)'}

So, Django applies DISTINCT on values already summed, while it shouls
apply DISTINCT BEFORE summing.


What do you think?

Note that my actual problem is that I have to apply aggregation on a
queryset which is provided by a 'black-box' function: the queryset is
already provided with the '__in' filter and the 'distinct' clause and
I cannot change its behaviour, nor taking distinct back...

Any suggestion?

Thanks a lot

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: values with distinct not working as expected

2010-07-30 Thread Scott Gould
You don't need order_by to get distinct values per se, but in this
case you need to put it in to override whatever default ordering you
have on your model (since any order_by fields will be included in the
query and thwart your distinct()).

On Jul 30, 3:52 am, tuxcanfly <tuxcan...@gmail.com> wrote:
> Thanks, that works!
>
> But I don't understand why I should order_by to get distinct values.
>
> On Jul 29, 3:59 pm, Subhranath Chunder <subhran...@gmail.com> wrote:
>
>
>
> > If you don't want to uniquify yourself, then why not simply do:
> > User.objects.values('username').order_by('username').distinct()
>
> > or, going the way that were already heading, it would be:
> > Visitor.objects.values('user__username').order_by('user__username'').distin 
> > ct()
>
> > Thanks,
> > Subhranath Chunder.
>
> > On Thu, Jul 29, 2010 at 2:29 PM, tuxcanfly <tuxcan...@gmail.com> wrote:
> > > I have this:
>
> > > class Visitor(models.Model):
> > >    user = models.ForeignKey(User)
> > >    ..
> > >    ..
>
> > > I'm trying to get the distinct usernames, so I did this:
>
> > >    Visitor.objects.values("user__username").distinct()
>
> > > But this stil gives me duplicate usernames. Of course I could use a
> > > flat values_list  and uniquify the result, but...
>
> > > --
> > > You received this message because you are subscribed to the Google Groups
> > > "Django users" group.
> > > To post to this group, send email to django-us...@googlegroups.com.
> > > To unsubscribe from this group, send email to
> > > django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@google
> > >  groups.com>
> > > .
> > > For more options, visit this group at
> > >http://groups.google.com/group/django-users?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: values with distinct not working as expected

2010-07-30 Thread tuxcanfly
Thanks, that works!

But I don't understand why I should order_by to get distinct values.

On Jul 29, 3:59 pm, Subhranath Chunder <subhran...@gmail.com> wrote:
> If you don't want to uniquify yourself, then why not simply do:
> User.objects.values('username').order_by('username').distinct()
>
> or, going the way that were already heading, it would be:
> Visitor.objects.values('user__username').order_by('user__username'').distin 
> ct()
>
> Thanks,
> Subhranath Chunder.
>
>
>
> On Thu, Jul 29, 2010 at 2:29 PM, tuxcanfly <tuxcan...@gmail.com> wrote:
> > I have this:
>
> > class Visitor(models.Model):
> >    user = models.ForeignKey(User)
> >    ..
> >    ..
>
> > I'm trying to get the distinct usernames, so I did this:
>
> >    Visitor.objects.values("user__username").distinct()
>
> > But this stil gives me duplicate usernames. Of course I could use a
> > flat values_list  and uniquify the result, but...
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@google 
> > groups.com>
> > .
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



values with distinct not working as expected

2010-07-29 Thread tuxcanfly
I have this:

class Visitor(models.Model):
user = models.ForeignKey(User)
..
..

I'm trying to get the distinct usernames, so I did this:

Visitor.objects.values("user__username").distinct()

But this stil gives me duplicate usernames. Of course I could use a
flat values_list  and uniquify the result, but...

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct() ?

2010-07-22 Thread Subhranath Chunder
With the other one, you would have got [u'ACTIVE', u'RESIGNED', u'TRANSFER']
without the unnecessary 'status' keyword each time.
Here you got only 3 results, but with more number of results, the 'status'
keyword each time would look annoying to me atleast.

But, I'm not sure which one will be faster. Can anyone please let me know,
which one would be faster. I'm not much considered about memory usage.

Thanks,
Subhranath Chunder.

On Thu, Jul 22, 2010 at 12:42 AM, rmschne <rmsc...@gmail.com> wrote:

> statuscodes=Member.objects.values('status').order_by('status').distinct()
>
> It gives me the expected results.  Three items in the dictionary from
> a database table of about 10,000 records:
> [{'status': u'ACTIVE'}, {'status': u'RESIGNED'}, {'status':
> u'TRANSFER'}]
>
> it's what i both expected and want.
>
> On Jul 21, 7:33 pm, Subhranath Chunder <subhran...@gmail.com> wrote:
> > I thought you were trying to get:
> >
> > I'm expecting only the four distinct records.
> >
> > You'll get a ValuesQuerySet or list of dictionaries with redundant keys
> this
> > way.
> >
> > Thanks,
> > Subhranath Chunder.
> >
> >
> >
> > On Wed, Jul 21, 2010 at 11:40 PM, rmschne <rmsc...@gmail.com> wrote:
> > > Member.objects.values('status').order_by('status').distinct()  from
> > > jaymzcd works perfectly. Thanks!
> >
> > > --
> > > You received this message because you are subscribed to the Google
> Groups
> > > "Django users" group.
> > > To post to this group, send email to django-us...@googlegroups.com.
> > > To unsubscribe from this group, send email to
> > > django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@googlegroups.com>
> <django-users%2bunsubscr...@google groups.com>
> > > .
> > > For more options, visit this group at
> > >http://groups.google.com/group/django-users?hl=en.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@googlegroups.com>
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct() ?

2010-07-21 Thread rmschne
statuscodes=Member.objects.values('status').order_by('status').distinct()

It gives me the expected results.  Three items in the dictionary from
a database table of about 10,000 records:
[{'status': u'ACTIVE'}, {'status': u'RESIGNED'}, {'status':
u'TRANSFER'}]

it's what i both expected and want.

On Jul 21, 7:33 pm, Subhranath Chunder <subhran...@gmail.com> wrote:
> I thought you were trying to get:
>
> I'm expecting only the four distinct records.
>
> You'll get a ValuesQuerySet or list of dictionaries with redundant keys this
> way.
>
> Thanks,
> Subhranath Chunder.
>
>
>
> On Wed, Jul 21, 2010 at 11:40 PM, rmschne <rmsc...@gmail.com> wrote:
> > Member.objects.values('status').order_by('status').distinct()  from
> > jaymzcd works perfectly. Thanks!
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@google 
> > groups.com>
> > .
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct() ?

2010-07-21 Thread Subhranath Chunder
I would have rather done something simple like:

set(Member.objects.values_list('status', flat=True))

Thanks,
Subhranath Chunder.

On Thu, Jul 22, 2010 at 12:03 AM, Subhranath Chunder
<subhran...@gmail.com>wrote:

> I thought you were trying to get:
>
> I'm expecting only the four distinct records.
>
> You'll get a ValuesQuerySet or list of dictionaries with redundant keys
> this way.
>
> Thanks,
> Subhranath Chunder.
>
> On Wed, Jul 21, 2010 at 11:40 PM, rmschne <rmsc...@gmail.com> wrote:
>
>> Member.objects.values('status').order_by('status').distinct()  from
>> jaymzcd works perfectly. Thanks!
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To post to this group, send email to django-us...@googlegroups.com.
>> To unsubscribe from this group, send email to
>> django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@googlegroups.com>
>> .
>> For more options, visit this group at
>> http://groups.google.com/group/django-users?hl=en.
>>
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct() ?

2010-07-21 Thread Subhranath Chunder
I thought you were trying to get:

I'm expecting only the four distinct records.

You'll get a ValuesQuerySet or list of dictionaries with redundant keys this
way.

Thanks,
Subhranath Chunder.

On Wed, Jul 21, 2010 at 11:40 PM, rmschne <rmsc...@gmail.com> wrote:

> Member.objects.values('status').order_by('status').distinct()  from
> jaymzcd works perfectly. Thanks!
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@googlegroups.com>
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct() ?

2010-07-21 Thread rmschne
Member.objects.values('status').order_by('status').distinct()  from
jaymzcd works perfectly. Thanks!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct() ?

2010-07-21 Thread Subhranath Chunder
>
>
> Member.objects.values('status').order_by('status').distinct()
>
>
I don't think this will ever work, to achieve what is required by him.

Thanks,
Subhranath

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct() ?

2010-07-21 Thread jaymzcd
"I've solved the problem by passing the returned dictionary through my
own distinct() function which strips out duplicates."

Don't roll your own implementations unless you actually really need
to! It's bad practise and can introduce added complexity to your
solution. The .distinct() call will work fine, you just need to order
correctly.

Also, if you needed to do something in sql that you couldnt get to
work via the django ORM i would use the new raw sql features so that
you at least get back queryset objects that you can use "as is" rather
than converting & flattening it to a dict and whatnot.

On 21 July, 18:29, rmschne <rmsc...@gmail.com> wrote:
> Yep.  (as I slap my forehead).
>
> I read that but erroneously concluded that since I had no sort_by on
> the query, I didn't pursue it.  There is a default ordering in the
> model.
> I've solved the problem by passing the returned dictionary through my
> own distinct() function which strips out duplicates.
>
> Thanks!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct() ?

2010-07-21 Thread jaymzcd
I'm guessing your Members model is referencing the User model? Check
the ordering as related models will influence your distinct. If your
Members model has its own ordering that will also come into effect
even though your picking your value out explicitly:

"If you order by fields from a related model, those fields will be
added to the selected columns and they may make otherwise duplicate
rows appear to be distinctThe moral here is that if you are using
distinct() be careful about ordering by related models. Similarly,
when using distinct() and values() together, be careful when ordering
by fields not in the values() call."

Member.objects.values('status').order_by('status').distinct()

Should give the correct count.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct() ?

2010-07-21 Thread rmschne
Yep.  (as I slap my forehead).

I read that but erroneously concluded that since I had no sort_by on
the query, I didn't pursue it.  There is a default ordering in the
model.
I've solved the problem by passing the returned dictionary through my
own distinct() function which strips out duplicates.

Thanks!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct() ?

2010-07-21 Thread Scott Gould
Does your model refer to any other fields for its default ordering?

http://docs.djangoproject.com/en/1.2/ref/models/querysets/#distinct


On Jul 21, 1:06 pm, rmschne <rmsc...@gmail.com> wrote:
> I'm trying to use the distinct() and it's giving me unexpected
> results.  Surely it's something simple, but I can't spot it.
>
> I've referred 
> tohttp://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct
>
> In SQL, it would be:
> select distinct status from members;
>
> in Django I am using:
> statuscodes=Member.objects.values('status').distinct()
>
> With SQL I get the four distinct values of status from the database I
> expect.
>
> In Django, I get back a dictionary with every record.  I'm expecting
> only the four distinct records.
>
> Any thoughts on what i'm doing wrong?
>
> Thanks!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



distinct() ?

2010-07-21 Thread rmschne
I'm trying to use the distinct() and it's giving me unexpected
results.  Surely it's something simple, but I can't spot it.

I've referred to 
http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct

In SQL, it would be:
select distinct status from members;

in Django I am using:
statuscodes=Member.objects.values('status').distinct()

With SQL I get the four distinct values of status from the database I
expect.

In Django, I get back a dictionary with every record.  I'm expecting
only the four distinct records.

Any thoughts on what i'm doing wrong?

Thanks!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: annotate with query set for distinct values

2010-06-11 Thread Scott Gould
It's not really a matter of "working around" it. Your .xxx method/
property is an attribute of the object. What you evidently want from
the database is *not* a list of those objects, but rather a summary
representation of them. Trying to apply your .xxx is meaningless as
you don't have a discrete object to apply it to. If it *is* supposed
to be meaningful in that context, then it's probably the sort of thing
that belongs in a manager.

If you can tell us a bit more about what .xxx actually is, or is
supposed to do, then we might be able to come up with an alternate
solution.

Regards
Scott


On Jun 10, 5:42 pm, SlafS <slaf...@gmail.com> wrote:
> Yes, I'm aware of the background of the problem but i was wondering if
> I can somehow "workaround" it.
>
> Thanks for Your help
>
> On 10 Cze, 23:34, Dan Harris <dih0...@gmail.com> wrote:
>
>
>
> > The problem is the GROUP BY you are looking to get. The problem with
> > doing a group by you don't get the whole object which is what the
> > Django queryset is trying to return:
>
> > res = queryset.annotate(Count("name"))
>
> > This will give you a result set that you want and you can iterate over
> > like:
>
> > {% for r in res %}
> >    {{ r.name }} - {{ r.name__count}}
> > {% endfor %}
>
> > however there may be duplicated {{ r.name }}
>
> > Dan Harris
> > dih0...@gmail.com
>
> > On Jun 10, 5:24 pm, SlafS <slaf...@gmail.com> wrote:
>
> > > Thanks.
>
> > > I've already tried that but this isn't quite what i'm looking for. As
> > > u wrote this returns a list, but I would like to obtain my calculated
> > > property when I'm iterating over this. Like so (let's say the result
> > > is in res variable) :
>
> > > {% for r in res %}
> > >    {{r.xxx}} - {{r.name__count}}
> > > {% endfor %}
>
> > > I'm starting to think that there's no such nice way to acheive that :/
>
> > > On 10 Cze, 23:06, Dan Harris <dih0...@gmail.com> wrote:
>
> > > > Here is an example:
>
> > > > # In models.py
> > > > class TestModel(models.Model):
> > > >    name = models.CharField()
>
> > > > # Get a listing of unique names and their counts
> > > > # In some view
> > > > from django.db.models import Count
>
> > > > TestModel.objects.values("name").annotate(Count("name"))
>
> > > > This will return a list of the form:
>
> > > > [{'name__count': 2, 'name': u''}, {'name__count': 1, 'name':
> > > > u'bbb'}]
>
> > > > Hope this helps!
>
> > > > Dan Harris
> > > > dih0...@gmail.com
>
> > > > On Jun 10, 5:01 pm, SlafS <slaf...@gmail.com> wrote:
>
> > > > > Hi there!
> > > > > I have a question. If i have a model with some fields (let's say all
> > > > > CharFields named aaa,bbb,ccc etc. and some calculated properties named
> > > > > xxx and zzz) how can I obtain something similar to
>
> > > > > "SELECT aaa, count(aaa) FROM my_model_table GROUP BY aaa;"
> > > > > i.e. a list of - lazy loaded - objects with distinct aaa values and an
> > > > > extra column which indicates how many entries of a specific aaa are in
> > > > > the table.
>
> > > > > I would like to acheive that with QuerySet and annotate so that I can
> > > > > get a list of objects to use their other properties (xxx or zzz) e.g.
> > > > > in my template
>
> > > > > Regards

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: annotate with query set for distinct values

2010-06-10 Thread sebastien piquemal
I think you didn't really look well anotate, because it looks like it
is what you qre looking for ! Or is there something I misunderstood ?

http://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate-args-kwargs

"Annotates each object in the QuerySet with the provided list of
aggregate values (averages, sums, etc) that have been computed over
the objects that are related to the objects in the QuerySet. Each
argument to annotate() is an annotation that will be added to each
object in the QuerySet that is returned."

On Jun 11, 12:24 am, SlafS <slaf...@gmail.com> wrote:
> Thanks.
>
> I've already tried that but this isn't quite what i'm looking for. As
> u wrote this returns a list, but I would like to obtain my calculated
> property when I'm iterating over this. Like so (let's say the result
> is in res variable) :
>
> {% for r in res %}
>    {{r.xxx}} - {{r.name__count}}
> {% endfor %}
>
> I'm starting to think that there's no such nice way to acheive that :/
>
> On 10 Cze, 23:06, Dan Harris <dih0...@gmail.com> wrote:
>
>
>
> > Here is an example:
>
> > # In models.py
> > class TestModel(models.Model):
> >    name = models.CharField()
>
> > # Get a listing of unique names and their counts
> > # In some view
> > from django.db.models import Count
>
> > TestModel.objects.values("name").annotate(Count("name"))
>
> > This will return a list of the form:
>
> > [{'name__count': 2, 'name': u''}, {'name__count': 1, 'name':
> > u'bbb'}]
>
> > Hope this helps!
>
> > Dan Harris
> > dih0...@gmail.com
>
> > On Jun 10, 5:01 pm, SlafS <slaf...@gmail.com> wrote:
>
> > > Hi there!
> > > I have a question. If i have a model with some fields (let's say all
> > > CharFields named aaa,bbb,ccc etc. and some calculated properties named
> > > xxx and zzz) how can I obtain something similar to
>
> > > "SELECT aaa, count(aaa) FROM my_model_table GROUP BY aaa;"
> > > i.e. a list of - lazy loaded - objects with distinct aaa values and an
> > > extra column which indicates how many entries of a specific aaa are in
> > > the table.
>
> > > I would like to acheive that with QuerySet and annotate so that I can
> > > get a list of objects to use their other properties (xxx or zzz) e.g.
> > > in my template
>
> > > Regards

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: annotate with query set for distinct values

2010-06-10 Thread SlafS
Yes, I'm aware of the background of the problem but i was wondering if
I can somehow "workaround" it.

Thanks for Your help

On 10 Cze, 23:34, Dan Harris <dih0...@gmail.com> wrote:
> The problem is the GROUP BY you are looking to get. The problem with
> doing a group by you don't get the whole object which is what the
> Django queryset is trying to return:
>
> res = queryset.annotate(Count("name"))
>
> This will give you a result set that you want and you can iterate over
> like:
>
> {% for r in res %}
>    {{ r.name }} - {{ r.name__count}}
> {% endfor %}
>
> however there may be duplicated {{ r.name }}
>
> Dan Harris
> dih0...@gmail.com
>
> On Jun 10, 5:24 pm, SlafS <slaf...@gmail.com> wrote:
>
> > Thanks.
>
> > I've already tried that but this isn't quite what i'm looking for. As
> > u wrote this returns a list, but I would like to obtain my calculated
> > property when I'm iterating over this. Like so (let's say the result
> > is in res variable) :
>
> > {% for r in res %}
> >    {{r.xxx}} - {{r.name__count}}
> > {% endfor %}
>
> > I'm starting to think that there's no such nice way to acheive that :/
>
> > On 10 Cze, 23:06, Dan Harris <dih0...@gmail.com> wrote:
>
> > > Here is an example:
>
> > > # In models.py
> > > class TestModel(models.Model):
> > >    name = models.CharField()
>
> > > # Get a listing of unique names and their counts
> > > # In some view
> > > from django.db.models import Count
>
> > > TestModel.objects.values("name").annotate(Count("name"))
>
> > > This will return a list of the form:
>
> > > [{'name__count': 2, 'name': u''}, {'name__count': 1, 'name':
> > > u'bbb'}]
>
> > > Hope this helps!
>
> > > Dan Harris
> > > dih0...@gmail.com
>
> > > On Jun 10, 5:01 pm, SlafS <slaf...@gmail.com> wrote:
>
> > > > Hi there!
> > > > I have a question. If i have a model with some fields (let's say all
> > > > CharFields named aaa,bbb,ccc etc. and some calculated properties named
> > > > xxx and zzz) how can I obtain something similar to
>
> > > > "SELECT aaa, count(aaa) FROM my_model_table GROUP BY aaa;"
> > > > i.e. a list of - lazy loaded - objects with distinct aaa values and an
> > > > extra column which indicates how many entries of a specific aaa are in
> > > > the table.
>
> > > > I would like to acheive that with QuerySet and annotate so that I can
> > > > get a list of objects to use their other properties (xxx or zzz) e.g.
> > > > in my template
>
> > > > Regards

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: annotate with query set for distinct values

2010-06-10 Thread Dan Harris
Here is an example:

# In models.py
class TestModel(models.Model):
   name = models.CharField()


# Get a listing of unique names and their counts
# In some view
from django.db.models import Count

TestModel.objects.values("name").annotate(Count("name"))

This will return a list of the form:

[{'name__count': 2, 'name': u''}, {'name__count': 1, 'name':
u'bbb'}]

Hope this helps!

Dan Harris
dih0...@gmail.com

On Jun 10, 5:01 pm, SlafS <slaf...@gmail.com> wrote:
> Hi there!
> I have a question. If i have a model with some fields (let's say all
> CharFields named aaa,bbb,ccc etc. and some calculated properties named
> xxx and zzz) how can I obtain something similar to
>
> "SELECT aaa, count(aaa) FROM my_model_table GROUP BY aaa;"
> i.e. a list of - lazy loaded - objects with distinct aaa values and an
> extra column which indicates how many entries of a specific aaa are in
> the table.
>
> I would like to acheive that with QuerySet and annotate so that I can
> get a list of objects to use their other properties (xxx or zzz) e.g.
> in my template
>
> Regards

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: annotate with query set for distinct values

2010-06-10 Thread Dan Harris
The problem is the GROUP BY you are looking to get. The problem with
doing a group by you don't get the whole object which is what the
Django queryset is trying to return:

res = queryset.annotate(Count("name"))

This will give you a result set that you want and you can iterate over
like:

{% for r in res %}
   {{ r.name }} - {{ r.name__count}}
{% endfor %}

however there may be duplicated {{ r.name }}

Dan Harris
dih0...@gmail.com

On Jun 10, 5:24 pm, SlafS <slaf...@gmail.com> wrote:
> Thanks.
>
> I've already tried that but this isn't quite what i'm looking for. As
> u wrote this returns a list, but I would like to obtain my calculated
> property when I'm iterating over this. Like so (let's say the result
> is in res variable) :
>
> {% for r in res %}
>    {{r.xxx}} - {{r.name__count}}
> {% endfor %}
>
> I'm starting to think that there's no such nice way to acheive that :/
>
> On 10 Cze, 23:06, Dan Harris <dih0...@gmail.com> wrote:
>
>
>
> > Here is an example:
>
> > # In models.py
> > class TestModel(models.Model):
> >    name = models.CharField()
>
> > # Get a listing of unique names and their counts
> > # In some view
> > from django.db.models import Count
>
> > TestModel.objects.values("name").annotate(Count("name"))
>
> > This will return a list of the form:
>
> > [{'name__count': 2, 'name': u''}, {'name__count': 1, 'name':
> > u'bbb'}]
>
> > Hope this helps!
>
> > Dan Harris
> > dih0...@gmail.com
>
> > On Jun 10, 5:01 pm, SlafS <slaf...@gmail.com> wrote:
>
> > > Hi there!
> > > I have a question. If i have a model with some fields (let's say all
> > > CharFields named aaa,bbb,ccc etc. and some calculated properties named
> > > xxx and zzz) how can I obtain something similar to
>
> > > "SELECT aaa, count(aaa) FROM my_model_table GROUP BY aaa;"
> > > i.e. a list of - lazy loaded - objects with distinct aaa values and an
> > > extra column which indicates how many entries of a specific aaa are in
> > > the table.
>
> > > I would like to acheive that with QuerySet and annotate so that I can
> > > get a list of objects to use their other properties (xxx or zzz) e.g.
> > > in my template
>
> > > Regards

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



annotate with query set for distinct values

2010-06-10 Thread SlafS
Hi there!
I have a question. If i have a model with some fields (let's say all
CharFields named aaa,bbb,ccc etc. and some calculated properties named
xxx and zzz) how can I obtain something similar to

"SELECT aaa, count(aaa) FROM my_model_table GROUP BY aaa;"
i.e. a list of - lazy loaded - objects with distinct aaa values and an
extra column which indicates how many entries of a specific aaa are in
the table.

I would like to acheive that with QuerySet and annotate so that I can
get a list of objects to use their other properties (xxx or zzz) e.g.
in my template

Regards

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: annotate with query set for distinct values

2010-06-10 Thread SlafS
Thanks.

I've already tried that but this isn't quite what i'm looking for. As
u wrote this returns a list, but I would like to obtain my calculated
property when I'm iterating over this. Like so (let's say the result
is in res variable) :

{% for r in res %}
   {{r.xxx}} - {{r.name__count}}
{% endfor %}

I'm starting to think that there's no such nice way to acheive that :/

On 10 Cze, 23:06, Dan Harris <dih0...@gmail.com> wrote:
> Here is an example:
>
> # In models.py
> class TestModel(models.Model):
>    name = models.CharField()
>
> # Get a listing of unique names and their counts
> # In some view
> from django.db.models import Count
>
> TestModel.objects.values("name").annotate(Count("name"))
>
> This will return a list of the form:
>
> [{'name__count': 2, 'name': u''}, {'name__count': 1, 'name':
> u'bbb'}]
>
> Hope this helps!
>
> Dan Harris
> dih0...@gmail.com
>
> On Jun 10, 5:01 pm, SlafS <slaf...@gmail.com> wrote:
>
> > Hi there!
> > I have a question. If i have a model with some fields (let's say all
> > CharFields named aaa,bbb,ccc etc. and some calculated properties named
> > xxx and zzz) how can I obtain something similar to
>
> > "SELECT aaa, count(aaa) FROM my_model_table GROUP BY aaa;"
> > i.e. a list of - lazy loaded - objects with distinct aaa values and an
> > extra column which indicates how many entries of a specific aaa are in
> > the table.
>
> > I would like to acheive that with QuerySet and annotate so that I can
> > get a list of objects to use their other properties (xxx or zzz) e.g.
> > in my template
>
> > Regards

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Distinct Field

2010-05-03 Thread Thales
Thank you very much. It worked fine.

On 3 maio, 07:50, "ge...@aquarianhouse.com" <ge...@aquarianhouse.com>
wrote:
> Did you try:
>
> Projct.objects.all().values('year').annotate(count=Count('year'))
>
> On May 3, 12:45 pm, Thales <thales@gmail.com> wrote:
>
>
>
> > I tried
> > Projct.objects.annotate(Count('year', distinct=True))
>
> > But it still returns all the rows...
>
> > If I execute the raw SQL "select distinct(year) from project" it works
> > fine, but I dont think its very elegant...
>
> > On 3 maio, 07:31, "ge...@aquarianhouse.com" <ge...@aquarianhouse.com>
> > wrote:
>
> > > To use distinct in this context is not a good idea.
>
> > > Better use aggregate and count the years.
>
> > >http://docs.djangoproject.com/en/dev/topics/db/aggregation/#generatin...
>
> > > On May 3, 12:27 pm, Thales <thales@gmail.com> wrote:
>
> > > > Hi everybody,
>
> > > > I have a model called "Project" with the field "year". I have
> > > > something about 1200 rows all of them with the year value "2010". But,
> > > > I'll start adding projects for other years.
>
> > > > I want to show the years that has projects, now it should just be:
> > > > 2010
>
> > > > I am trying to do this:
> > > > p = Project.objects.values('year').distinct()
> > > > But it returns me 1200 rows! How should I do to just get one row for
> > > > each year in the table?
>
> > > > Thanks!
>
> > > > --
> > > > You received this message because you are subscribed to the Google 
> > > > Groups "Django users" group.
> > > > To post to this group, send email to django-us...@googlegroups.com.
> > > > To unsubscribe from this group, send email to 
> > > > django-users+unsubscr...@googlegroups.com.
> > > > For more options, visit this group 
> > > > athttp://groups.google.com/group/django-users?hl=en.
>
> > > --
> > > You received this message because you are subscribed to the Google Groups 
> > > "Django users" group.
> > > To post to this group, send email to django-us...@googlegroups.com.
> > > To unsubscribe from this group, send email to 
> > > django-users+unsubscr...@googlegroups.com.
> > > For more options, visit this group 
> > > athttp://groups.google.com/group/django-users?hl=en.
>
> > --
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group 
> athttp://groups.google.com/group/django-users?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Distinct Field

2010-05-03 Thread ge...@aquarianhouse.com
Did you try:

Projct.objects.all().values('year').annotate(count=Count('year'))

On May 3, 12:45 pm, Thales <thales@gmail.com> wrote:
> I tried
> Projct.objects.annotate(Count('year', distinct=True))
>
> But it still returns all the rows...
>
> If I execute the raw SQL "select distinct(year) from project" it works
> fine, but I dont think its very elegant...
>
> On 3 maio, 07:31, "ge...@aquarianhouse.com" <ge...@aquarianhouse.com>
> wrote:
>
>
>
> > To use distinct in this context is not a good idea.
>
> > Better use aggregate and count the years.
>
> >http://docs.djangoproject.com/en/dev/topics/db/aggregation/#generatin...
>
> > On May 3, 12:27 pm, Thales <thales@gmail.com> wrote:
>
> > > Hi everybody,
>
> > > I have a model called "Project" with the field "year". I have
> > > something about 1200 rows all of them with the year value "2010". But,
> > > I'll start adding projects for other years.
>
> > > I want to show the years that has projects, now it should just be:
> > > 2010
>
> > > I am trying to do this:
> > > p = Project.objects.values('year').distinct()
> > > But it returns me 1200 rows! How should I do to just get one row for
> > > each year in the table?
>
> > > Thanks!
>
> > > --
> > > You received this message because you are subscribed to the Google Groups 
> > > "Django users" group.
> > > To post to this group, send email to django-us...@googlegroups.com.
> > > To unsubscribe from this group, send email to 
> > > django-users+unsubscr...@googlegroups.com.
> > > For more options, visit this group 
> > > athttp://groups.google.com/group/django-users?hl=en.
>
> > --
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group 
> athttp://groups.google.com/group/django-users?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Distinct Field

2010-05-03 Thread Thales
I tried
Projct.objects.annotate(Count('year', distinct=True))

But it still returns all the rows...

If I execute the raw SQL "select distinct(year) from project" it works
fine, but I dont think its very elegant...

On 3 maio, 07:31, "ge...@aquarianhouse.com" <ge...@aquarianhouse.com>
wrote:
> To use distinct in this context is not a good idea.
>
> Better use aggregate and count the years.
>
> http://docs.djangoproject.com/en/dev/topics/db/aggregation/#generatin...
>
> On May 3, 12:27 pm, Thales <thales@gmail.com> wrote:
>
>
>
> > Hi everybody,
>
> > I have a model called "Project" with the field "year". I have
> > something about 1200 rows all of them with the year value "2010". But,
> > I'll start adding projects for other years.
>
> > I want to show the years that has projects, now it should just be:
> > 2010
>
> > I am trying to do this:
> > p = Project.objects.values('year').distinct()
> > But it returns me 1200 rows! How should I do to just get one row for
> > each year in the table?
>
> > Thanks!
>
> > --
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group 
> athttp://groups.google.com/group/django-users?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Distinct Field

2010-05-03 Thread ge...@aquarianhouse.com
To use distinct in this context is not a good idea.

Better use aggregate and count the years.

http://docs.djangoproject.com/en/dev/topics/db/aggregation/#generating-aggregates-over-a-queryset

On May 3, 12:27 pm, Thales <thales@gmail.com> wrote:
> Hi everybody,
>
> I have a model called "Project" with the field "year". I have
> something about 1200 rows all of them with the year value "2010". But,
> I'll start adding projects for other years.
>
> I want to show the years that has projects, now it should just be:
> 2010
>
> I am trying to do this:
> p = Project.objects.values('year').distinct()
> But it returns me 1200 rows! How should I do to just get one row for
> each year in the table?
>
> Thanks!
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group 
> athttp://groups.google.com/group/django-users?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Distinct Field

2010-05-03 Thread Thales
Hi everybody,

I have a model called "Project" with the field "year". I have
something about 1200 rows all of them with the year value "2010". But,
I'll start adding projects for other years.

I want to show the years that has projects, now it should just be:
2010

I am trying to do this:
p = Project.objects.values('year').distinct()
But it returns me 1200 rows! How should I do to just get one row for
each year in the table?

Thanks!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django Distinct on queryset in forms.py

2010-03-30 Thread Thomas
Dear,

Look at my first post i had .distinct() into it and it didn't work
out, it's pretty obvious why, he does the distinct on the primary key
field (ID) and not on the field hostname, so i get no SELECT Distinct
result as i would like to. Trust me the only way of doing this is my
2nd post or the following should work aswell:
choices=Test.objects.values_list('hostname', 'hostname').distinct() ,
required=False

Regards

On Mar 30, 5:47 pm, "pjrhar...@gmail.com" <pjrhar...@gmail.com> wrote:
> On Mar 30, 2:10 pm, Thomas <thomasje...@gmail.com> wrote:
>
> > I already found a solution by myself:
>
> > doing this into the forms.py inside the class does the trick:
>
> >         def __init__(self, *args, **kwargs):
> >                 super(FilterForm, self) .__init__(*args, **kwargs)
> >                 self.fields['host'].choices =
> > Test.objects.values_list('hostname', 'hostname').distinct()
>
> You don't need anything that complicated, the original code just had a
> mistake- you need to put the ".distinct()" at the end of the query,
> not the field definition!
>
> Compare:
>
> orms.ModelMultipleChoiceField(queryset=Events.objects.values('hostname'),
> required=False).distinct()
>
> and:
>
> orms.ModelMultipleChoiceField(queryset=Events.objects.values('hostname').distinct(),
> required=False)
>
> Peter

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django Distinct on queryset in forms.py

2010-03-30 Thread pjrhar...@gmail.com


On Mar 30, 2:10 pm, Thomas <thomasje...@gmail.com> wrote:
> I already found a solution by myself:
>
> doing this into the forms.py inside the class does the trick:
>
>         def __init__(self, *args, **kwargs):
>                 super(FilterForm, self) .__init__(*args, **kwargs)
>                 self.fields['host'].choices =
> Test.objects.values_list('hostname', 'hostname').distinct()

You don't need anything that complicated, the original code just had a
mistake- you need to put the ".distinct()" at the end of the query,
not the field definition!

Compare:

orms.ModelMultipleChoiceField(queryset=Events.objects.values('hostname'),
required=False).distinct()

and:

orms.ModelMultipleChoiceField(queryset=Events.objects.values('hostname').distinct(),
required=False)

Peter

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django Distinct on queryset in forms.py

2010-03-30 Thread Thomas
I already found a solution by myself:

doing this into the forms.py inside the class does the trick:

def __init__(self, *args, **kwargs):
super(FilterForm, self) .__init__(*args, **kwargs)
self.fields['host'].choices =
Test.objects.values_list('hostname', 'hostname').distinct()


On Mar 30, 10:32 am, Thomas <thomasje...@gmail.com> wrote:
> Hi all,
>
> I try to get a list with distinct into the forms.py like this:
>
> forms.ModelMultipleChoiceField(queryset=Events.objects.values('hostname'),
> required=False).distinct()
>
> In the python shell this command works perfect, but when trying it in
> forms.py leaves me a blank form, so nothing appears. When i just do
> Events.objects.all() the form appears, but distinct doesn't work with
> Events.objects.all()... i also tried values_list etc but doesn't seem
> to fit into the forms neither... anyone got an idea how to get a
> SELECT DISTINCT into a ModelMultipleChoiceField?
>
> I read some other questions about this at stackoverflow but nothing
> seems to work out with me, so hopefully someone knows how to do this
> in forms.py.
>
> Thxs in advance

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django Distinct on queryset in forms.py

2010-03-30 Thread Thomas
Hi all,

I try to get a list with distinct into the forms.py like this:

forms.ModelMultipleChoiceField(queryset=Events.objects.values('hostname'),
required=False).distinct()

In the python shell this command works perfect, but when trying it in
forms.py leaves me a blank form, so nothing appears. When i just do
Events.objects.all() the form appears, but distinct doesn't work with
Events.objects.all()... i also tried values_list etc but doesn't seem
to fit into the forms neither... anyone got an idea how to get a
SELECT DISTINCT into a ModelMultipleChoiceField?

I read some other questions about this at stackoverflow but nothing
seems to work out with me, so hopefully someone knows how to do this
in forms.py.

Thxs in advance

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django Sum all values with a distinct ForeignKey ID & zip them with fields from related table

2010-03-29 Thread Gramware
I would like to perform something similar to
http://stackoverflow.com/questions/861310/summing-the-values-from-the-2nd-table-based-on-id-of-the-1st-table
(ie get the sum of distinct event amounts in a payment table then
group the payments by event details and total money paid for them.
Also getting users and what they have paid for an event will be done)
in Django using PostgreSQL.

My models are as below:

class UserProfile(User):
onames = models.CharField(max_length=30, blank=True)
phoneNumber = models.CharField(max_length=15, blank=True)
regNo = models.CharField(max_length=15)
designation =
models.CharField(max_length=3,choices=DESIGNATION_CHOICES,
default='MEM')
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/
%d', blank=True, null=True, default='photos/2010/03/placeholder.jpg')
course = models.CharField(max_length=30, blank=True, null=True)
timezone = models.CharField(max_length=50, default='Africa/
Nairobi')
smsCom = models.BooleanField()
mailCom = models.BooleanField()

class Payments(models.Model):
username = models.ForeignKey(UserProfile, related_name='payer')
receiptNo = models.CharField(max_length=30, primary_key=True)
particulars = models.CharField(max_length=50)
date = models.DateField(auto_now_add=True)
amount = models.FloatField(max_length=99, blank=True)
eventID = models.ForeignKey('events', null=True, blank=True)
receiver = models.ForeignKey(UserProfile,
related_name='receiver')
deleted = models.BooleanField()

class events(models.Model):
eventName  = models.CharField(max_length=100)
eventID =  models.AutoField(primary_key=True)
details = models.TextField()
attendanceFee = models.FloatField(max_length=99)
date = models.DateField()
username = models.ManyToManyField(UserProfile,
related_name='user')
eventposter = models.ForeignKey(UserProfile,
related_name='event_poster')
deleted = models.BooleanField()

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Most Recent Distinct Results

2010-02-21 Thread max
Hi,
I have a list of "news" matches for certain companies, ordered by the
date they were found.  I want to grab 5 results for each company up to
5 companies.  I initially approached this problem by just grabbing a
large amount of the newest results (LIMIT 100 or so) and then, through
python, grouping them into lists for each company.  However, this has
a pitfall in that if one company has most of the results for the last
100 newest results, I will only have one company in the final set,
rather than 5.

I thought I might be able to use  DISTINCT query and do something like

Match.objects.filter(type='company').values('contact_id__company').order_by('-
added_date').distinct()[:5]

To get the newest 5 companies mentioned, and then take those names and
do some more queries for each company.  But that has a failure that
I've read about in the docs (http://docs.djangoproject.com/en/dev/
topics/db/aggregation/#interaction-with-default-ordering-or-order-by)

I also tried an annotate method like this:

Match.objects.filter(client_id__pk=42,
result_type='company').order_by('-
added_date').values('contact_id__company').annotate().order_by('contact_id__company')

But the problem with this is that I can't LIMIT after I sort by order,
so I end up just getting a DISTINCT list of all companies that have
Match objects for them.

Is there another way I could do this, where I'm guaranteed at least 5
distinct company names sorted by the date news was found for them?

Thanks.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: distinct related objects [solved]

2009-12-10 Thread andreas
and i solved it in the view. dont know if this is the right way but it
works:

def topic_detail(request, slug):
topic = get_object_or_404(Topic, slug=slug)
t = topic.project_set.all()
techlist = []
for p in t:
for t in  p.technologies.all():
if t in techlist:
pass
else:
techlist.append(t)
return object_list(request,
   queryset=topic.project_set.all(),
   template_name='myapp/topic_detail.html',
   extra_context={'object': topic, 'techlist':
techlist })



On Dec 10, 12:18 pm, andreas schmid <a.schmi...@gmail.com> wrote:
> ok im still stucking on this one:
>
> i dont think the regroup tag can help in this case
> but i cant understand how i can query the technologies used within a
> specific topic.
>
> i mean i have alredy the projects assigned to this topic, now i need the
> technologies used by this projects.
>
> any ideas?
>
> Tim Valenta wrote:
> > It looks like the problem is that you're trying to group by
> > Technology, but your queryset is in Projects.  You could experiment
> > with the "regroup" template tag
> > (http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
> > )
>
> > It's a little hard to understand at first, but I think it's pretty
> > much what you're trying to do.  You would be able to remove the
> > ".distinct" part of your query because dictionary keys are already
> > can't be doubled.
>
> > Hope that helps.
>
> > Tim
>
> > On Nov 26, 7:04 am, andreas schmid <a.schmi...@gmail.com> wrote:
>
> >> hi,
>
> >> i have a question about retrieving related objects avoiding double entries.
> >> actually i have 3 models:
> >>     topics
> >>     projects
> >>     technologies
>
> >> the projects model has foreignkeys to topics and technologies. i have a
> >> view for the topic detail like this:
>
> >>     def topic_detail(request, slug):
> >>         topic = get_object_or_404(Topic, slug=slug)
> >>         return object_list(request,
> >>                            queryset=topic.project_set.all(),
> >>                            paginate_by=20,
> >>                            template_name='FSlabs/topic_detail.html',
> >>                            extra_context={ 'topic': topic })
>
> >> in the template i can loop trough the projects and  get those  assigned
> >> to this topic.
> >> but im having problems to retrieve the technologies used by those
> >> projects without having double entries.
>
> >> i tried this in the template with a list for every project
> >> assigned...which of course is not what i want:
>
> >>     {% for project in object_list  %}
> >>             {% for technology in project.technologies.distinct %}
> >>                 {{
> >>     technology.title }}
> >>                 {% if forloop.last %}{% else %}
> >>                 {% ifequal forloop.revcounter0 1 %}and {% else %}, {%
> >>     endifequal %}
> >>                 {% endif %}
> >>             {% endfor %}
> >>         {% endfor %}
>
> >> can somebody point me to the right way to get what i need?
>
> >> thx
>
> > --
>
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.
>
>

--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: distinct related objects

2009-12-10 Thread andreas schmid
ok im still stucking on this one:

i dont think the regroup tag can help in this case
but i cant understand how i can query the technologies used within a
specific topic.

i mean i have alredy the projects assigned to this topic, now i need the
technologies used by this projects.

any ideas?


Tim Valenta wrote:
> It looks like the problem is that you're trying to group by
> Technology, but your queryset is in Projects.  You could experiment
> with the "regroup" template tag
> ( http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
> )
>
> It's a little hard to understand at first, but I think it's pretty
> much what you're trying to do.  You would be able to remove the
> ".distinct" part of your query because dictionary keys are already
> can't be doubled.
>
> Hope that helps.
>
> Tim
>
> On Nov 26, 7:04 am, andreas schmid <a.schmi...@gmail.com> wrote:
>   
>> hi,
>>
>> i have a question about retrieving related objects avoiding double entries.
>> actually i have 3 models:
>> topics
>> projects
>> technologies
>>
>> the projects model has foreignkeys to topics and technologies. i have a
>> view for the topic detail like this:
>>
>> def topic_detail(request, slug):
>> topic = get_object_or_404(Topic, slug=slug)
>> return object_list(request,
>>queryset=topic.project_set.all(),
>>paginate_by=20,
>>template_name='FSlabs/topic_detail.html',
>>extra_context={ 'topic': topic })
>>
>> in the template i can loop trough the projects and  get those  assigned
>> to this topic.
>> but im having problems to retrieve the technologies used by those
>> projects without having double entries.
>>
>> i tried this in the template with a list for every project
>> assigned...which of course is not what i want:
>>
>> {% for project in object_list  %}
>> {% for technology in project.technologies.distinct %}
>> {{
>> technology.title }}
>> {% if forloop.last %}{% else %}
>> {% ifequal forloop.revcounter0 1 %}and {% else %}, {%
>> endifequal %}
>> {% endif %}
>> {% endfor %}
>> {% endfor %}
>>
>> can somebody point me to the right way to get what i need?
>>
>> thx
>> 
>
> --
>
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>
>
>   

--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: distinct related objects

2009-11-27 Thread Tim Valenta
It looks like the problem is that you're trying to group by
Technology, but your queryset is in Projects.  You could experiment
with the "regroup" template tag
( http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
)

It's a little hard to understand at first, but I think it's pretty
much what you're trying to do.  You would be able to remove the
".distinct" part of your query because dictionary keys are already
can't be doubled.

Hope that helps.

Tim

On Nov 26, 7:04 am, andreas schmid <a.schmi...@gmail.com> wrote:
> hi,
>
> i have a question about retrieving related objects avoiding double entries.
> actually i have 3 models:
>     topics
>     projects
>     technologies
>
> the projects model has foreignkeys to topics and technologies. i have a
> view for the topic detail like this:
>
>     def topic_detail(request, slug):
>         topic = get_object_or_404(Topic, slug=slug)
>         return object_list(request,
>                            queryset=topic.project_set.all(),
>                            paginate_by=20,
>                            template_name='FSlabs/topic_detail.html',
>                            extra_context={ 'topic': topic })
>
> in the template i can loop trough the projects and  get those  assigned
> to this topic.
> but im having problems to retrieve the technologies used by those
> projects without having double entries.
>
> i tried this in the template with a list for every project
> assigned...which of course is not what i want:
>
>     {% for project in object_list  %}
>             {% for technology in project.technologies.distinct %}
>                 {{
>     technology.title }}
>                 {% if forloop.last %}{% else %}
>                 {% ifequal forloop.revcounter0 1 %}and {% else %}, {%
>     endifequal %}
>                 {% endif %}
>             {% endfor %}
>         {% endfor %}
>
> can somebody point me to the right way to get what i need?
>
> thx

--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




distinct related objects

2009-11-26 Thread andreas schmid
hi,

i have a question about retrieving related objects avoiding double entries.
actually i have 3 models:
topics
projects
technologies

the projects model has foreignkeys to topics and technologies. i have a
view for the topic detail like this:

def topic_detail(request, slug):
topic = get_object_or_404(Topic, slug=slug)
return object_list(request,
   queryset=topic.project_set.all(),
   paginate_by=20,
   template_name='FSlabs/topic_detail.html',
   extra_context={ 'topic': topic })

in the template i can loop trough the projects and  get those  assigned
to this topic.
but im having problems to retrieve the technologies used by those
projects without having double entries.

i tried this in the template with a list for every project
assigned...which of course is not what i want:

{% for project in object_list  %}
{% for technology in project.technologies.distinct %}
{{
technology.title }}
{% if forloop.last %}{% else %}
{% ifequal forloop.revcounter0 1 %}and {% else %}, {%
endifequal %}
{% endif %}
{% endfor %}
{% endfor %}

can somebody point me to the right way to get what i need?

thx

--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: querySet + select distinct

2009-11-20 Thread Bill Freeman
On Fri, Nov 20, 2009 at 2:47 AM, Andy McKay <a...@clearwind.ca> wrote:
> On 09-11-19 3:36 PM, Benjamin Wolf wrote:
...
>
> Try using values in the filter eg:
>
> Disposal.objects.values("mydate").filter(mydate__year__gte=2008).distinct()
>
> The problem is the default django query selects all the fields, messing
> up the distinct part.
>

If you happen to be in PostgreSQL, might you be able to put "DISTINCT ON" in an
.extra() where?  Of course, you have to know what the ORM is calling
the columns.

Bill

--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=.




  1   2   >