Re: query on models

2014-05-07 Thread Davide Scatto
Do you start from Ques model? What are your starting data?

Il giorno mercoledì 7 maggio 2014 15:24:38 UTC+2, Anushree ha scritto:
>
> I have the following models. I want to retrieve list of question banks 
> related to a particular subject. Is it possible to do without modifying the 
> existing data models?Thank you
> class Subject(models.Model):
> name = models.CharField(max_length = 255)
> desc = models.TextField(blank=True)
> def __unicode__(self):
> return self.name
>
> class QuestionBank(models.Model):
> name = models.CharField(max_length=255)
> desc = models.TextField()
> def __unicode__(self):
> return self.name
>
> class Ques(models.Model):
> content = models.TextField()
> ques_type = models.CharField(max_length = 1 , default= 'A')
> score = models.PositiveSmallIntegerField(max_length = 1 , default= 1)
> ques_bank = models.ForeignKey(QuestionBank)
> subject = models.ForeignKey(Subject)
>

-- 
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/f98ca810-27a1-45a2-a177-cef5ba365456%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: query on models

2014-05-07 Thread Rafael E. Ferrero
Just filtering Ques model (imho)

--
Rafael E. Ferrero


2014-05-07 10:24 GMT-03:00 Anushree :

> I have the following models. I want to retrieve list of question banks
> related to a particular subject. Is it possible to do without modifying the
> existing data models?Thank you
> class Subject(models.Model):
> name = models.CharField(max_length = 255)
> desc = models.TextField(blank=True)
> def __unicode__(self):
> return self.name
>
> class QuestionBank(models.Model):
> name = models.CharField(max_length=255)
> desc = models.TextField()
> def __unicode__(self):
> return self.name
>
> class Ques(models.Model):
> content = models.TextField()
> ques_type = models.CharField(max_length = 1 , default= 'A')
> score = models.PositiveSmallIntegerField(max_length = 1 , default= 1)
> ques_bank = models.ForeignKey(QuestionBank)
> subject = models.ForeignKey(Subject)
>
> --
> 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/66442114-cda1-45c4-9320-1059c045e48a%40googlegroups.com
> .
> 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/CAJJc_8WPAZcJnfXND1VAdfASK31VuQ1HR1So%3DYykgxcSXEMSxw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


query on models

2014-05-07 Thread Anushree
I have the following models. I want to retrieve list of question banks 
related to a particular subject. Is it possible to do without modifying the 
existing data models?Thank you
class Subject(models.Model):
name = models.CharField(max_length = 255)
desc = models.TextField(blank=True)
def __unicode__(self):
return self.name

class QuestionBank(models.Model):
name = models.CharField(max_length=255)
desc = models.TextField()
def __unicode__(self):
return self.name

class Ques(models.Model):
content = models.TextField()
ques_type = models.CharField(max_length = 1 , default= 'A')
score = models.PositiveSmallIntegerField(max_length = 1 , default= 1)
ques_bank = models.ForeignKey(QuestionBank)
subject = models.ForeignKey(Subject)

-- 
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/66442114-cda1-45c4-9320-1059c045e48a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django Query Data

2014-05-05 Thread C. Kirby
The reason you are getting a dictionary in return is because the call to 
values() returns a ValueQuerySet, which is an iterable of dictionaries (
https://docs.djangoproject.com/en/dev/ref/models/querysets/#values)
In order to get a list of tee colors (eg ['Blue',Green','Red']) you should 
use a value_list(). values_list usually returns a list of tuple, but if you 
are only asking for a single field you can give it the flat flag, which 
flattens the tuples into just the field value. (
https://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list)

Taken all together, your query should be:
teecolors = 
GolfCourseTees.objects.filter(Course_Name=course).values_list('Tee_Color', 
flat=True)

Kirby

On Saturday, May 3, 2014 7:47:07 PM UTC-5, Brendan Edwards wrote:
>
> Hi,
>  
> I have just started learning Django (been flip flopping between meteor and 
> django, cant decide which to use..) and I am fairly new to web development 
> in general.
>  
> Basically, I have a query where I am using the code "teecolor = 
> GolfCourseTees.objects.values('Tee_Color').filter(Course_Name=course)" but 
> I want to take the value retrieved form this and use it to make another 
> query before loading the template. When I set color1= teecolor[0] color 1 
> will show as: {'Tee_Color': u'Blue'}, and I am unsure why this happens. I 
> want to retrieve only the value "blue" in this case.
>  
> The reason for this is each course has usualy 4-5 tee colors. therefore I 
> will have color1 = teecolor[0], color 2 = teecolor[1] etc.. so that I can 
> insert that into a second query. To do that these values need to be "blue" 
> "black" etc
>  
> Questions:
>  
> 1) What is the data "{'Tee_Color': u'Blue'}" output "{'Tee_Color': 
> u'Blue'}" called and why does it display like this (I would like to 
> understand and not just insert a given line of code)? I have read the 
> documentation and I am still confused on this. 
> 2) How can I retrieve blue from {'Tee_Color': u'Blue'}? (example code 
> would be helpful)
> Brendan
>  
>

-- 
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/5dc76b9c-c4c0-4637-b390-572aabea1a3e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Django Query Data

2014-05-04 Thread Brendan Edwards
Hi,
 
I have just started learning Django (been flip flopping between meteor and 
django, cant decide which to use..) and I am fairly new to web development 
in general.
 
Basically, I have a query where I am using the code "teecolor = 
GolfCourseTees.objects.values('Tee_Color').filter(Course_Name=course)" but 
I want to take the value retrieved form this and use it to make another 
query before loading the template. When I set color1= teecolor[0] color 1 
will show as: {'Tee_Color': u'Blue'}, and I am unsure why this happens. I 
want to retrieve only the value "blue" in this case.
 
The reason for this is each course has usualy 4-5 tee colors. therefore I 
will have color1 = teecolor[0], color 2 = teecolor[1] etc.. so that I can 
insert that into a second query. To do that these values need to be "blue" 
"black" etc
 
Questions:
 
1) What is the data "{'Tee_Color': u'Blue'}" output "{'Tee_Color': 
u'Blue'}" called and why does it display like this (I would like to 
understand and not just insert a given line of code)? I have read the 
documentation and I am still confused on this. 
2) How can I retrieve blue from {'Tee_Color': u'Blue'}? (example code would 
be helpful)
Brendan
 

-- 
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/2d92f660-db45-4c23-9525-f6f42fac5bca%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


SQL query to authenticate user from non-django app

2014-04-28 Thread Goran Mekic
Hi,

I have a Django project with its DB. How can I use Django DB users to
auth, for example, vsftpd? I mean, I couldn't find suitable SQL query to
check the password. Thank you!


signature.asc
Description: Digital signature


Re: Casting a raw query set as a list for pagination

2014-04-26 Thread Matt Buck
I've created a paginator for RawQuerySets. 
 https://github.com/seamusmb/django-paginator-rawqueryset

On Tuesday, March 26, 2013 5:51:41 AM UTC-4, chambe...@gmail.com wrote:
>
> I'm trying to implement Django's built in pagination feature with a raw 
> query set. I've researched the issue and the answer is I need to cast my 
> set as a list. Something like this:
>
> paginator = Paginator(refg, 100) # Show 100 contacts per page
> paginator._count = len(list(refg))
>
> From my understanding, setting the count field for the paginator should 
> prevent Django from trying to get the size of my raw set, but this is not the 
> case.  I'm still getting the "RawQuerySet has no len() operation" error.  
> I've attched the relevant code from my views.py and my template.  
>
> Can I get some advice as to how I can fix this error?
>
>
> views.py
> refg = RefGene.objects.raw(qrefg) 
>
> paginator = Paginator(refg, 100) # Show 100 contacts per page 
> paginator._count = len(list(refg)) 
>
> # using django's generated forms 
> c = RequestContext(request, { 
> "refg": refg, ... }) 
>
> return HttpResponse(t.render(c)) 
>
>
> template
>
> {% autopaginate refg %}
> {% for r in refg %}
>
> 
> {{ r.data}}
> {{ r.loc}}
> 
>
> {% endfor %}
> {% paginate %}
>
>

-- 
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/86cd1c6d-5e2d-409c-8ce7-f911c61fe856%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Tastypie with Django and MongoDB. How to query subdocuments

2014-04-02 Thread Juan M. Mendez
Hello, I made this question with more details on stackoverflow: 

https://stackoverflow.com/questions/22792828/best-subdocument-structure-to-query-django-tastypie-with-mongodb-backend

It could be summarized on this: 

I want to create an structure with Django and Tastypie  that allows to have 
documents with subdocuments in mongoDB
that can be queried on the client through backbone.js.

What's the best approach you use?

Many thanks.

-- 
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/d78718cc-b09b-477e-bc1e-ebe0b1eba9ea%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: User Profiles "user.get_profile()" returns 'matching query does not exist.'

2014-03-28 Thread Brian Sanchez
try:

except:

it worked
thank you!!

On Saturday, September 20, 2008 9:14:42 PM UTC-4, Paddy Joy wrote:
>
> The error message is telling you that the user has no profile 
> (Specifically there is no record in the table schedule.profile related 
> to the user). 
>
> Your app needs to take care of creating the user profile, even if it 
> going to be empty. What I have done in my case is I force the user to 
> create a profile when they first log on by checking if the profile 
> exists. 
>
> # Check if logged in user has profile, if not redirect to 
> create profile 
> try: 
> profile = request.user.get_profile() 
> except: 
> return HttpResponseRedirect("/createprofile/") 
>
>
> Paddy 
>
> On Sep 21, 8:48 am, mclovin  wrote: 
> > I have spent about 2 hours on this so far, but havent been able to get 
> > it right, my model is: 
> > 
> > (located in schedule/models.py, stripped down to just the profile) 
> > 
> > from django.contrib.auth.models import User 
> > class profile(models.Model): 
> > user = models.ForeignKey(User, unique=True) 
> > aim = models.CharField(max_length=100, blank=True) 
> > website = models.CharField(max_length=100, blank=True) 
> > 
> > and i have this as my setting: 
> > AUTH_PROFILE_MODULE = 'schedule.profile' 
> > 
> > I did a syncdb and it showed the profile successfully being added... 
> > 
> > then i did in "python manage.py shell": 
> > from django.contrib.auth.models import User 
> > u = User.objects.get(pk=1) 
> > print u.get_profile().aim 
> > 
> > but I get this error: 
> > Traceback (most recent call last): 
> >   File "", line 1, in  
> >   File "/usr/lib/python2.5/site-packages/django/contrib/auth/ 
> > models.py", line 293, in get_profile 
> > self._profile_cache = 
> > model._default_manager.get(user__id__exact=self.id) 
> >   File "/usr/lib/python2.5/site-packages/django/db/models/manager.py", 
> > line 93, in get 
> > return self.get_query_set().get(*args, **kwargs) 
> >   File "/usr/lib/python2.5/site-packages/django/db/models/query.py", 
> > line 303, in get 
> > % self.model._meta.object_name) 
> > DoesNotExist: profile matching query does not exist. 
> > 
> > anyone have any idea what is wrong?

-- 
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/050e7c6c-8dc0-43dc-a20f-f6e3c7475b6a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How allow public query & download of info from my db

2014-03-21 Thread Rafael E. Ferrero
2014-03-21 12:19 GMT-03:00 C. Kirby :

> I've actually built a small app that generates a form allowing users to do
> a Meta Query on models django-modelqueryform.
> I am in the process of a full rewrite of it to make it a lot more
> customizable, but the initial version works with fields that have choices
> set or with fields that are a numeric type. The resulting form provides
> each of the fields in you models with either a multichoicefield (choices)
> or a multifield widget which has a min, max and allow None checkbox. Right
> now I do not handle text based fields.
>
> You can find the code and documentation (as it is) at
> https://github.com/ckirby/django-modelqueryform
>
> Even if you can't use this directly, I think the code can give you some
> ideas.
>
> Hope it helps!
>
> On Friday, March 21, 2014 3:49:17 AM UTC-5, Venkatraman.S. wrote:
>
>>
>> On Fri, Mar 21, 2014 at 12:17 AM, Nicholas Tapia wrote:
>>
>>> Hey Django Community!
>>>
>>> I'm newer to programming and was pointed in the direction of django for
>>> this project.
>>>
>>> The idea is that people can make their own custom queries and download
>>> load it from my db.
>>>
>>> So far I'm thinking that using a form is they way to go to accept this
>>> information.  But from there I'm a little confused.  Does a custom model
>>> need to be created automatically before that query can be requested and
>>> displayed?  Or can model be skipped in this case?
>>>
>>>
>>>
>> The Q is very abstract and you need to refine it if you need better
>> guidance.
>>
>> From what I understand, it looks to me that you have a database and have
>> been asked to provide an interface from which customers can download data.
>> If yes, the best possible way to have filters so that customers can define
>> their queries based on these filters and download the related dataset. Do
>> NOT expose an interface by which customers can key-in a SQL and download
>> data.
>>
>> More on hearing from you.
>>
>> -V
>>
>>
>  --
> 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/bb22e4ba-3602-4181-82e9-18b335667705%40googlegroups.com<https://groups.google.com/d/msgid/django-users/bb22e4ba-3602-4181-82e9-18b335667705%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>
> For more options, visit https://groups.google.com/d/optout.
>

Nicholas, if you do an interface where user can write his own custom sql
querys its an open door for sql inyection... indeed, you were facilitating
his work :P

What Venkatraman says is (more or lest) what Kirby does, so IMHO you must
to go in that way.

Cheers!,

Saludos Cordiales,
--
Rafael E. Ferrero

-- 
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/CAJJc_8UhjcCTJLN%2BFY3JPfyinb3UTeCV8S7J1NH2GwFdujGxPg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How allow public query & download of info from my db

2014-03-21 Thread C. Kirby
I've actually built a small app that generates a form allowing users to do 
a Meta Query on models django-modelqueryform.
I am in the process of a full rewrite of it to make it a lot more 
customizable, but the initial version works with fields that have choices 
set or with fields that are a numeric type. The resulting form provides 
each of the fields in you models with either a multichoicefield (choices) 
or a multifield widget which has a min, max and allow None checkbox. Right 
now I do not handle text based fields.

You can find the code and documentation (as it is) at 
https://github.com/ckirby/django-modelqueryform

Even if you can't use this directly, I think the code can give you some 
ideas.

Hope it helps!

On Friday, March 21, 2014 3:49:17 AM UTC-5, Venkatraman.S. wrote:
>
>
> On Fri, Mar 21, 2014 at 12:17 AM, Nicholas Tapia 
> 
> > wrote:
>
>> Hey Django Community!
>>
>> I'm newer to programming and was pointed in the direction of django for 
>> this project.
>>
>> The idea is that people can make their own custom queries and download 
>> load it from my db.
>>
>> So far I'm thinking that using a form is they way to go to accept this 
>> information.  But from there I'm a little confused.  Does a custom model 
>> need to be created automatically before that query can be requested and 
>> displayed?  Or can model be skipped in this case?
>>
>>
>>
> The Q is very abstract and you need to refine it if you need better 
> guidance.
>
> From what I understand, it looks to me that you have a database and have 
> been asked to provide an interface from which customers can download data. 
> If yes, the best possible way to have filters so that customers can define 
> their queries based on these filters and download the related dataset. Do 
> NOT expose an interface by which customers can key-in a SQL and download 
> data.
>
> More on hearing from you.
>
> -V
>  
>

-- 
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/bb22e4ba-3602-4181-82e9-18b335667705%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How allow public query & download of info from my db

2014-03-21 Thread Venkatraman S
On Fri, Mar 21, 2014 at 12:17 AM, Nicholas Tapia
wrote:

> Hey Django Community!
>
> I'm newer to programming and was pointed in the direction of django for
> this project.
>
> The idea is that people can make their own custom queries and download
> load it from my db.
>
> So far I'm thinking that using a form is they way to go to accept this
> information.  But from there I'm a little confused.  Does a custom model
> need to be created automatically before that query can be requested and
> displayed?  Or can model be skipped in this case?
>
>
>
The Q is very abstract and you need to refine it if you need better
guidance.

>From what I understand, it looks to me that you have a database and have
been asked to provide an interface from which customers can download data.
If yes, the best possible way to have filters so that customers can define
their queries based on these filters and download the related dataset. Do
NOT expose an interface by which customers can key-in a SQL and download
data.

More on hearing from you.

-V

-- 
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/CAN7tdFSvaridyVcdxcY%3Dds5iwMP0JmtzivjYniAb-AEwAJWTzg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


How allow public query & download of info from my db

2014-03-20 Thread Nicholas Tapia
Hey Django Community!

I'm newer to programming and was pointed in the direction of django for 
this project.

The idea is that people can make their own custom queries and download load 
it from my db.

So far I'm thinking that using a form is they way to go to accept this 
information.  But from there I'm a little confused.  Does a custom model 
need to be created automatically before that query can be requested and 
displayed?  Or can model be skipped in this case?

Thank you Django Community!

-Nicholas

-- 
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/47751b42-0ff7-465a-8dda-337d3e8d9d5d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to convert SQL Complex QUERY to django QUERY

2014-03-18 Thread Shoaib Ijaz


I am trying to convert sql query to django query but failed to do this, can 
anyone help me

select id,name,round(value::numeric,2) as value, st_transform(geometry, 3857) 
as geometry
from net_rest
where state_id in (1,2) and name = 'height'
union
(select d.id,d.restriction,d.value, st_transform(d.geometry, 3857) as 
geometry from display_rest d
where d.restriction='height' and condition_id not in (select 
condition_id 
from net_rest_conditions where version_id = 2)

OR This

select id,name,value as value, geometry
from net_rest
where state_id in (1,2) and name = 'height'
union
(select d.id,d.restriction,d.value,geometry from display_rest d
where d.restriction='height' and condition_id not in (select 
condition_id 
from net_rest_conditions where version_id = 2)

*Updated the question fro here*

I am using django django rest framework serialize *net_rest* Model, 
basically i am working on project related to GIS where i have to make rest 
api to expose data

Here is some of my models

class net_rest(models.Model):
name = models.CharField(max_length=50, blank=True)
value = models.FloatField()
state_id = models.IntegerField(null=True, blank=True)
geometry = models.GeometryField(null=True, blank=True)
objects = models.GeoManager()

class Meta:
db_table = u'tbl_net_rest'

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


class display_rest(models.Model):
restriction = models.CharField(max_length=45, blank=True)
link_id = models.IntegerField(blank=True, null=True)
condition_id = models.IntegerField(blank=True, null=True)
value = models.FloatField(blank=True, null=True)
geometry = models.GeometryField(blank=True, null=True)
class Meta:
db_table = u'tbl_display_rest'


class net_rest_conditions(models.Model):
condition_id = models.IntegerField()
version_id =  models.IntegerField(blank=True, null=True)
class Meta:
db_table = u'tbl_net_rest_conditions'
class networkSerializer(serializers.GeoModelSerializer):
class Meta:
model = net_rest
fields = ('id', 'name', 'value', 'geometry')

Here is view

class networkSerializerViewSet(viewsets.ModelViewSet):

q1 = display_rest.objects.values_list('id', 'name', 'value', 
'geometry').filter(restriction='height')\

.exclude(condition_id__in=net_rest_conditions.objects.filter(version_id=2).values_list('condition_id',flat=True))

q2 = net_rest.objects.all().filter(Q(name="height"), Q(state_id=1) | 
Q(state_id=2)).values_list('id', 'value', 'geometry')

queryset = q1 | q2

serializer_class = networkSerializer

-- 
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/6e137e70-e88d-49bb-b000-e6174aae3837%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: RAW query to non default DB

2014-03-07 Thread Tom Evans
On Fri, Mar 7, 2014 at 3:31 PM, bikeridercz  wrote:
> Dear colleagues,
>
> I'm trying to do a direct select do database other than the default one. But
> it fails with error.
>
> Note 1: "ASSETS.objects.using('vodb').filter(...)" works fine
> Note 2: the select is little tricky and unfortunately cannot be replaced by
> a database view, because I have no access to database. This is the reason
> why I need the "raw" feature
>
> Example (select is simpified):
> assets = ASSETS.objects.using('vodb').raw('select a.msisdn from ASSET a
> where a.subscription_id_unique = %s', [msisdn])
>
> Error: 'QuerySet' object has no attribute 'raw'
>
> DJango version: 1.6.2

Foo.objects.raw(…).using(…)

Cheers

Tom

-- 
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/CAFHbX1%2BgtzSuhJNQANrcUVqEH4Cx0T_2wjGew9rHkA%2BgZ9Cm%3DQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


RAW query to non default DB

2014-03-07 Thread bikeridercz
Dear colleagues,

I'm trying to do a direct select do database other than the default one. 
But it fails with error.

Note 1: "ASSETS.objects*.using('vodb')*.filter(...)" works fine
Note 2: the select is little tricky and unfortunately cannot be replaced by 
a database view, because I have no access to database. This is the reason 
why I need the "raw" feature

*Example (select is simpified):*
assets = ASSETS.objects*.using('vodb')*.raw('select a.msisdn from ASSET a 
where a.subscription_id_unique = %s', [msisdn])

*Error:* 'QuerySet' object has no attribute 'raw'

*DJango version: *1.6.2

-- 
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/2cedb92a-5f2c-46b5-a457-a2d15bc26554%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Django Site(s) looks ugly with ?None as query parameter.

2014-03-06 Thread Christian Schmitt
Hello, currently I have some Django sites one of them 
is http://www.schnooge-hansili.de/ if i open it 
with http://www.schnooge-hansili.de/?None It looks really ugly. Currently 
the first site is just a simple CBV view. Nothing really special.

-- 
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/cedd2c00-f95f-4582-b8b4-9845b2f39f75%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Optimizing DB query involving annotate and aggregate

2014-02-11 Thread ST
Managed it in the end, so for reference here is what I ended up with:

def total_credit_debt(self):
transaction_totals = 
Transaction.objects.filter(member__isnull=False).values('member').annotate(total=Sum('amount')).order_by()
creditors = transaction_totals.filter(total__gt=0)
debtors = transaction_totals.filter(total__lt=0)
total_credit = sum(row['total'] for row in creditors)
total_debt = sum(row['total'] for row in debtors)
return total_credit, total_debt

(@classmethod on TransactionManager)

Unfortunately I didn't manage to get it to do the second sum inside the 
database as well, but this is fast enough - there's only a few hundred 
members with non-zero balances. If you think there's any way this could be 
improved / cleaned up, I'd be happy to hear:)

Thanks!


On Thursday, February 6, 2014 7:59:37 PM UTC, arnonym wrote:
>
> On Wed, 5 Feb 2014 10:11:29 -0800 (PST) ST 
> > 
>
> wrote: 
> > Hi, 
> > 
> > I'm trying to optimize the run-time of getting total credit and debt 
> > values out of our database. Ideally I'd like to formulate it as a 
> > Django query. This is the raw SQL query I have, which produces the 
> > right answer and is very fast (milliseconds): 
> > 
> > SELECT sum(tg.total) FROM 
> >   ( 
> >   SELECT sum(t.amount) AS total, t.member_id AS member_id 
> >   FROM club_transaction AS t 
> >   WHERE t.member_id IS NOT NULL 
> >   GROUP BY t.member_id 
> >   ) AS tg 
> > WHERE tg.total < 0 
> > 
> > (plus a second query for > 0) 
> > 
> > My Django implementation was: 
> > 
> > m = 
> > Member.objects.annotate(balance=Sum('transaction__amount')) m_debt = 
> > m.filter(balance__lt=0).aggregate(total=Sum('balance')) m_credit = 
> > m.filter(balance__gt=0).aggregate(total=Sum('balance')) 
> > 
> > which looks a lot nicer, is easier to understand and maintain. 
> > 
> > However, it results in the following SQL query (slightly redacted): 
> > 
> > SELECT SUM(balance) FROM 
> >   ( 
> >   SELECT "club_member"."id" AS "id", {all the other fields}, 
> > SUM("club_transaction"."amount") AS "balance" 
> >   FROM "club_member" 
> >   LEFT OUTER JOIN "auth_user" ON ("club_member"."user_id" = 
> > "auth_user"."id") 
> >   LEFT OUTER JOIN "club_transaction" ON ("club_member"."id" = 
> > "club_transaction"."member_id") 
> >   GROUP BY "club_member"."id", {all the other fields}, 
> > "auth_user"."last_name", "auth_user"."first_name" 
> >   HAVING SUM("club_transaction"."amount") < 0 
> >   ORDER BY "auth_user"."last_name" ASC, "auth_user"."first_name" ASC 
> >   ) subquery 
> > 
> > (again, plus another one for > 0) 
> > which is very slow (almost 1.5 seconds). 
> > 
> > How can I construct a Django query which doesn't request (and group 
> > by) all the unnecessary other fields ? 
> > I already tried playing around with only() and values() but never got 
> > it to work. 
>
> I did something similar a few years back. Its next to impossible with 
> django-orm, just do it in raw sql. 
> The django-orm can't really do any advanced group_by clauses. And you 
> can't give them with extra(). Well, you can give them but they won't be 
> used;-) 
>
> Doing two (or three) orm-queries and then joining the data in python 
> will actually be slower then doing it all in hand-crafted sql. 
>
> So just do the sql by hand. And then optimize by having three columns, 
> one with the SUM(amount) if amount>0, one with the SUM(amount) if 
> amount<0 and one with the SUM(amount). Total credits, total depts and 
> balance all in one query (if possible)... 
>
> - Arnold 
>

-- 
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/73bd4ddb-d6ee-461a-bed3-a3ee915b8859%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Optimizing DB query involving annotate and aggregate

2014-02-06 Thread Arnold Krille
On Wed, 5 Feb 2014 10:11:29 -0800 (PST) ST 
wrote:
> Hi,
> 
> I'm trying to optimize the run-time of getting total credit and debt
> values out of our database. Ideally I'd like to formulate it as a
> Django query. This is the raw SQL query I have, which produces the
> right answer and is very fast (milliseconds):
> 
> SELECT sum(tg.total) FROM
>   (
>   SELECT sum(t.amount) AS total, t.member_id AS member_id
>   FROM club_transaction AS t
>   WHERE t.member_id IS NOT NULL
>   GROUP BY t.member_id
>   ) AS tg
> WHERE tg.total < 0
> 
> (plus a second query for > 0)
> 
> My Django implementation was:
> 
> m =
> Member.objects.annotate(balance=Sum('transaction__amount')) m_debt =
> m.filter(balance__lt=0).aggregate(total=Sum('balance')) m_credit =
> m.filter(balance__gt=0).aggregate(total=Sum('balance'))
> 
> which looks a lot nicer, is easier to understand and maintain.
> 
> However, it results in the following SQL query (slightly redacted):
> 
> SELECT SUM(balance) FROM
>   (
>   SELECT "club_member"."id" AS "id", {all the other fields}, 
> SUM("club_transaction"."amount") AS "balance"
>   FROM "club_member"
>   LEFT OUTER JOIN "auth_user" ON ("club_member"."user_id" = 
> "auth_user"."id")
>   LEFT OUTER JOIN "club_transaction" ON ("club_member"."id" = 
> "club_transaction"."member_id")
>   GROUP BY "club_member"."id", {all the other fields}, 
> "auth_user"."last_name", "auth_user"."first_name"
>   HAVING SUM("club_transaction"."amount") < 0
>   ORDER BY "auth_user"."last_name" ASC, "auth_user"."first_name" ASC
>   ) subquery
> 
> (again, plus another one for > 0)
> which is very slow (almost 1.5 seconds).
> 
> How can I construct a Django query which doesn't request (and group
> by) all the unnecessary other fields ?
> I already tried playing around with only() and values() but never got
> it to work.

I did something similar a few years back. Its next to impossible with
django-orm, just do it in raw sql.
The django-orm can't really do any advanced group_by clauses. And you
can't give them with extra(). Well, you can give them but they won't be
used;-)

Doing two (or three) orm-queries and then joining the data in python
will actually be slower then doing it all in hand-crafted sql.

So just do the sql by hand. And then optimize by having three columns,
one with the SUM(amount) if amount>0, one with the SUM(amount) if
amount<0 and one with the SUM(amount). Total credits, total depts and
balance all in one query (if possible)...

- Arnold


signature.asc
Description: PGP signature


Re: Optimizing DB query involving annotate and aggregate

2014-02-06 Thread Erik Cederstrand
Den 06/02/2014 kl. 12.34 skrev ST :

> This didn't work - it produced a "SELECT  FROM" query, which obviously didn't 
> work - tried adding 'amount' to the values_list, but that didn't help either. 
> Eventually got it to work by using .only('member', 'amount') instead, and it 
> *was* fast, but it didn't quite do what we need: we only want the 
> *outstanding* credit/debt, i.e. some member might have many transactions, but 
> they all add up to zero - so instead of increasing both total_debt and 
> total_credit by that value, it shouldn't affect the totals. Which is why I 
> wanted to total up by members first... any idea how to get that to work ?

Instead of spending a lot of time trying to bend the Django ORM to do what you 
want, just keep the raw SQL that you know works, and add tests to your test 
suite. The ORM is really nice, but sometimes it's just not worth the hassle.

Erik

-- 
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/FE4FC4FE-AD80-421B-A32C-7EFE299F20EC%40cederstrand.dk.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Optimizing DB query involving annotate and aggregate

2014-02-06 Thread ST
On Wednesday, February 5, 2014 8:01:53 PM UTC, Anssi Kääriäinen wrote:
>
> Something like this might work:
> 
> Transaction.objects.values_list('member_id').annotate(total=Sum('amount')).filter(total__gt=0).aggregate(Sum('total'))
>

This didn't work - it produced a "SELECT  FROM" query, which obviously 
didn't work - tried adding 'amount' to the values_list, but that didn't 
help either. Eventually got it to work by using .only('member', 'amount') 
instead, and it *was* fast, but it didn't quite do what we need: we only 
want the *outstanding* credit/debt, i.e. some member might have many 
transactions, but they all add up to zero - so instead of increasing both 
total_debt and total_credit by that value, it shouldn't affect the totals. 
Which is why I wanted to total up by members first... any idea how to get 
that to work ?

 

>
> That is, don't start from Member, Django isn't smart enough to get rid of 
> the non-necessary joins. Instead go directly for the query you wrote in 
> SQL. In the ORM .values() is the way to control GROUP BY clause. Getting 
> the order of .values() and .annotate() right is important, and it is 
> sometimes hard to figure out how to do it correctly. Also, if you have some 
> extra ordering going on in the query just issue an empty .order_by() call - 
> that will get rid of all ordering.
>
>  - Anssi
>
> On Wednesday, February 5, 2014 8:11:29 PM UTC+2, ST wrote:
>>
>> Hi,
>>
>> I'm trying to optimize the run-time of getting total credit and debt 
>> values out of our database. Ideally I'd like to formulate it as a Django 
>> query. This is the raw SQL query I have, which produces the right answer 
>> and is very fast (milliseconds):
>>
>> SELECT sum(tg.total) FROM
>>   (
>>   SELECT sum(t.amount) AS total, t.member_id AS member_id
>>   FROM club_transaction AS t
>>   WHERE t.member_id IS NOT NULL
>>   GROUP BY t.member_id
>>   ) AS tg
>> WHERE tg.total < 0
>>
>> (plus a second query for > 0)
>>
>> My Django implementation was:
>>
>> m = Member.objects.annotate(balance=Sum('transaction__amount'))
>> m_debt = m.filter(balance__lt=0).aggregate(total=Sum('balance'))
>> m_credit = m.filter(balance__gt=0).aggregate(total=Sum('balance'))
>>
>> which looks a lot nicer, is easier to understand and maintain.
>>
>> However, it results in the following SQL query (slightly redacted):
>>
>> SELECT SUM(balance) FROM
>>   (
>>   SELECT "club_member"."id" AS "id", {all the other fields}, 
>> SUM("club_transaction"."amount") AS "balance"
>>   FROM "club_member"
>>   LEFT OUTER JOIN "auth_user" ON ("club_member"."user_id" = 
>> "auth_user"."id")
>>   LEFT OUTER JOIN "club_transaction" ON ("club_member"."id" = 
>> "club_transaction"."member_id")
>>   GROUP BY "club_member"."id", {all the other fields}, 
>> "auth_user"."last_name", "auth_user"."first_name"
>>   HAVING SUM("club_transaction"."amount") < 0
>>   ORDER BY "auth_user"."last_name" ASC, "auth_user"."first_name" ASC
>>   ) subquery
>>
>> (again, plus another one for > 0)
>> which is very slow (almost 1.5 seconds).
>>
>> How can I construct a Django query which doesn't request (and group by) 
>> all the unnecessary other fields ?
>> I already tried playing around with only() and values() but never got it 
>> to work.
>>
>> Looking forward to your responses!
>>
>> best regards,
>> ST
>>
>

-- 
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/3e239afe-037c-4ace-b9eb-ac2404f75981%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Optimizing DB query involving annotate and aggregate

2014-02-05 Thread Anssi Kääriäinen
Something like this might work:

Transaction.objects.values_list('member_id').annotate(total=Sum('amount')).filter(total__gt=0).aggregate(Sum('total'))

That is, don't start from Member, Django isn't smart enough to get rid of 
the non-necessary joins. Instead go directly for the query you wrote in 
SQL. In the ORM .values() is the way to control GROUP BY clause. Getting 
the order of .values() and .annotate() right is important, and it is 
sometimes hard to figure out how to do it correctly. Also, if you have some 
extra ordering going on in the query just issue an empty .order_by() call - 
that will get rid of all ordering.

 - Anssi

On Wednesday, February 5, 2014 8:11:29 PM UTC+2, ST wrote:
>
> Hi,
>
> I'm trying to optimize the run-time of getting total credit and debt 
> values out of our database. Ideally I'd like to formulate it as a Django 
> query. This is the raw SQL query I have, which produces the right answer 
> and is very fast (milliseconds):
>
> SELECT sum(tg.total) FROM
>   (
>   SELECT sum(t.amount) AS total, t.member_id AS member_id
>   FROM club_transaction AS t
>   WHERE t.member_id IS NOT NULL
>   GROUP BY t.member_id
>   ) AS tg
> WHERE tg.total < 0
>
> (plus a second query for > 0)
>
> My Django implementation was:
>
> m = Member.objects.annotate(balance=Sum('transaction__amount'))
> m_debt = m.filter(balance__lt=0).aggregate(total=Sum('balance'))
> m_credit = m.filter(balance__gt=0).aggregate(total=Sum('balance'))
>
> which looks a lot nicer, is easier to understand and maintain.
>
> However, it results in the following SQL query (slightly redacted):
>
> SELECT SUM(balance) FROM
>   (
>   SELECT "club_member"."id" AS "id", {all the other fields}, 
> SUM("club_transaction"."amount") AS "balance"
>   FROM "club_member"
>   LEFT OUTER JOIN "auth_user" ON ("club_member"."user_id" = 
> "auth_user"."id")
>   LEFT OUTER JOIN "club_transaction" ON ("club_member"."id" = 
> "club_transaction"."member_id")
>   GROUP BY "club_member"."id", {all the other fields}, 
> "auth_user"."last_name", "auth_user"."first_name"
>   HAVING SUM("club_transaction"."amount") < 0
>   ORDER BY "auth_user"."last_name" ASC, "auth_user"."first_name" ASC
>   ) subquery
>
> (again, plus another one for > 0)
> which is very slow (almost 1.5 seconds).
>
> How can I construct a Django query which doesn't request (and group by) 
> all the unnecessary other fields ?
> I already tried playing around with only() and values() but never got it 
> to work.
>
> Looking forward to your responses!
>
> best regards,
> ST
>

-- 
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/ed49abcb-2089-4c4f-a46a-7ba67f3caa81%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Optimizing DB query involving annotate and aggregate

2014-02-05 Thread ST
Hi,

I'm trying to optimize the run-time of getting total credit and debt values 
out of our database. Ideally I'd like to formulate it as a Django query. 
This is the raw SQL query I have, which produces the right answer and is 
very fast (milliseconds):

SELECT sum(tg.total) FROM
  (
  SELECT sum(t.amount) AS total, t.member_id AS member_id
  FROM club_transaction AS t
  WHERE t.member_id IS NOT NULL
  GROUP BY t.member_id
  ) AS tg
WHERE tg.total < 0

(plus a second query for > 0)

My Django implementation was:

m = Member.objects.annotate(balance=Sum('transaction__amount'))
m_debt = m.filter(balance__lt=0).aggregate(total=Sum('balance'))
m_credit = m.filter(balance__gt=0).aggregate(total=Sum('balance'))

which looks a lot nicer, is easier to understand and maintain.

However, it results in the following SQL query (slightly redacted):

SELECT SUM(balance) FROM
  (
  SELECT "club_member"."id" AS "id", {all the other fields}, 
SUM("club_transaction"."amount") AS "balance"
  FROM "club_member"
  LEFT OUTER JOIN "auth_user" ON ("club_member"."user_id" = 
"auth_user"."id")
  LEFT OUTER JOIN "club_transaction" ON ("club_member"."id" = 
"club_transaction"."member_id")
  GROUP BY "club_member"."id", {all the other fields}, 
"auth_user"."last_name", "auth_user"."first_name"
  HAVING SUM("club_transaction"."amount") < 0
  ORDER BY "auth_user"."last_name" ASC, "auth_user"."first_name" ASC
  ) subquery

(again, plus another one for > 0)
which is very slow (almost 1.5 seconds).

How can I construct a Django query which doesn't request (and group by) all 
the unnecessary other fields ?
I already tried playing around with only() and values() but never got it to 
work.

Looking forward to your responses!

best regards,
ST

-- 
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/367c1f59-870c-40d1-9a53-4feb08890f29%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query friends of an user

2013-12-17 Thread C. Kirby
Oh, ok. You can do it from the other side then.

#32 is replaced with the User id you are interested in
User.object.filter(friendship__friend__pk = 32, friendship__status__in = 
[Friendship.FRIEND, Friendship.FAVORITE])

On Tuesday, December 17, 2013 11:53:11 AM UTC-6, Arthur Silva wrote:
>
> Thanks for your reply.
> Your suggestion works but I need the friends (User models) of a given user 
> (User model) in this case.
> This join (friends of an user) is also used at several other places to get 
> stuff (comments for example) made by friends of an user.
>
> --
> Arthur Pires Ribeiro Silva
> Universidade Federal de Uberlândia
> (34) 9187-4731
>
>
> On Tue, Dec 17, 2013 at 2:51 PM, C. Kirby  >wrote:
>
>> Why not just Friendship.objects.filter(user__pk = 32, status__in = 
>> [Friendship.FRIEND, Friendship.FAVORITE]) That will give you a QuerySet of 
>> all the friendships a user has. If you just want the list of friends then 
>> extend that query with a values_list like so:
>>
>> Friendship.objects.filter(user__pk = 32, status__in = [Friendship.FRIEND, 
>> Friendship.FAVORITE]) .values_list('friend', flat=True)
>>
>>
>>
>> On Tuesday, December 17, 2013 8:50:09 AM UTC-6, Arthur Silva wrote:
>>>
>>>  I want to query the friends of an User but I'm struggling to get the 
>>> correct query.
>>>
>>> Models:
>>>
>>> class User(AbstractUser, TimestampedModel, SerializeMixin):
>>> city = models.CharField(max_length=60, blank=True)
>>> picture = models.URLField(blank=True)
>>> cover_picture = models.URLField(blank=True)
>>> phone = models.CharField(max_length=20, blank=True)
>>> access_token = models.CharField(max_length=32, blank=True, 
>>> null=True, db_index=True)
>>> facebook_token = models.CharField(max_length=1024, blank=True, 
>>> null=True)
>>> facebook_id = models.BigIntegerField(blank=True, null=True, 
>>> db_index=True)
>>> twitter_token = models.CharField(max_length=1024, blank=True, 
>>> null=True)
>>> twitter_id = models.BigIntegerField(blank=True, null=True, 
>>> unique=True)
>>> friends = models.ManyToManyField("self", through="Friendship", 
>>> symmetrical=False)
>>>
>>>
>>> class Friendship(TimestampedModel, SerializeMixin):
>>> PENDING = "pending"
>>> FRIEND = "friend"
>>> FAVORITE = "favorite"
>>> STATUS_CHOICES = (
>>> (PENDING, "Pending"),
>>> (FRIEND, "Friend"),
>>> (FAVORITE, "Favorite")
>>> )
>>> user = models.ForeignKey(User, related_name="friendships")
>>> friend = models.ForeignKey(User, related_name="friendships_reverse")
>>> status = models.CharField(max_length=20, default=PENDING, 
>>> choices=STATUS_CHOICES)
>>>
>>>
>>> Query I'm trying to make
>>>
>>> id = 32 # I want friends from this user
>>> friends = User.objects.extra(select={"friendship_status": 
>>> "status"}). \
>>> filter(Q(friendships_reverse__user_id=id), 
>>> ~Q(friendships_reverse__status=Friendship.PENDING))
>>>
>>>
>>> But the generated query is quite weird:
>>>
>>> SELECT (status) AS `friendship_status`,
>>>`myapp_user`.`id`,
>>>`myapp_user`.`password`,
>>>`myapp_user`.`last_login`,
>>>`myapp_user`.`is_superuser`,
>>>`myapp_user`.`username`,
>>>`myapp_user`.`first_name`,
>>>`myapp_user`.`last_name`,
>>>`myapp_user`.`email`,
>>>`myapp_user`.`is_staff`,
>>>`myapp_user`.`is_active`,
>>>`myapp_user`.`date_joined`,
>>>`myapp_user`.`created_at`,
>>>`myapp_user`.`updated_at`,
>>>`myapp_user`.`city`,
>>>`myapp_user`.`picture`,
>>>`myapp_user`.`cover_picture`,
>>>`myapp_user`.`phone`,
>>>`myapp_user`.`access_token`,
>>>`myapp_user`.`facebook_token`,
>>>`myapp_user`.`facebook_id`,
>>>`myapp_user`.`twitter_token`,
>>>`myapp_user`.`twitter_id`
>>> FROM `myapp_user`
>>> INNER JOIN `myapp_friendship` ON (`myapp_user`.`id` = 
>>> `myapp_friendship`.`friend_id`)
>>> WHERE (`myapp_friendshi

Re: Query friends of an user

2013-12-17 Thread Arthur Silva
Thanks for your reply.
Your suggestion works but I need the friends (User models) of a given user
(User model) in this case.
This join (friends of an user) is also used at several other places to get
stuff (comments for example) made by friends of an user.

--
Arthur Pires Ribeiro Silva
Universidade Federal de Uberlândia
(34) 9187-4731


On Tue, Dec 17, 2013 at 2:51 PM, C. Kirby  wrote:

> Why not just Friendship.objects.filter(user__pk = 32, status__in =
> [Friendship.FRIEND, Friendship.FAVORITE]) That will give you a QuerySet of
> all the friendships a user has. If you just want the list of friends then
> extend that query with a values_list like so:
>
> Friendship.objects.filter(user__pk = 32, status__in = [Friendship.FRIEND,
> Friendship.FAVORITE]) .values_list('friend', flat=True)
>
>
>
> On Tuesday, December 17, 2013 8:50:09 AM UTC-6, Arthur Silva wrote:
>>
>>  I want to query the friends of an User but I'm struggling to get the
>> correct query.
>>
>> Models:
>>
>> class User(AbstractUser, TimestampedModel, SerializeMixin):
>> city = models.CharField(max_length=60, blank=True)
>> picture = models.URLField(blank=True)
>> cover_picture = models.URLField(blank=True)
>> phone = models.CharField(max_length=20, blank=True)
>> access_token = models.CharField(max_length=32, blank=True,
>> null=True, db_index=True)
>> facebook_token = models.CharField(max_length=1024, blank=True,
>> null=True)
>> facebook_id = models.BigIntegerField(blank=True, null=True,
>> db_index=True)
>> twitter_token = models.CharField(max_length=1024, blank=True,
>> null=True)
>> twitter_id = models.BigIntegerField(blank=True, null=True,
>> unique=True)
>> friends = models.ManyToManyField("self", through="Friendship",
>> symmetrical=False)
>>
>>
>> class Friendship(TimestampedModel, SerializeMixin):
>> PENDING = "pending"
>> FRIEND = "friend"
>> FAVORITE = "favorite"
>> STATUS_CHOICES = (
>> (PENDING, "Pending"),
>> (FRIEND, "Friend"),
>> (FAVORITE, "Favorite")
>> )
>> user = models.ForeignKey(User, related_name="friendships")
>> friend = models.ForeignKey(User, related_name="friendships_reverse")
>> status = models.CharField(max_length=20, default=PENDING,
>> choices=STATUS_CHOICES)
>>
>>
>> Query I'm trying to make
>>
>> id = 32 # I want friends from this user
>> friends = User.objects.extra(select={"friendship_status":
>> "status"}). \
>> filter(Q(friendships_reverse__user_id=id),
>> ~Q(friendships_reverse__status=Friendship.PENDING))
>>
>>
>> But the generated query is quite weird:
>>
>> SELECT (status) AS `friendship_status`,
>>`myapp_user`.`id`,
>>`myapp_user`.`password`,
>>`myapp_user`.`last_login`,
>>`myapp_user`.`is_superuser`,
>>`myapp_user`.`username`,
>>`myapp_user`.`first_name`,
>>`myapp_user`.`last_name`,
>>`myapp_user`.`email`,
>>`myapp_user`.`is_staff`,
>>`myapp_user`.`is_active`,
>>`myapp_user`.`date_joined`,
>>`myapp_user`.`created_at`,
>>`myapp_user`.`updated_at`,
>>`myapp_user`.`city`,
>>`myapp_user`.`picture`,
>>`myapp_user`.`cover_picture`,
>>`myapp_user`.`phone`,
>>`myapp_user`.`access_token`,
>>`myapp_user`.`facebook_token`,
>>`myapp_user`.`facebook_id`,
>>`myapp_user`.`twitter_token`,
>>`myapp_user`.`twitter_id`
>> FROM `myapp_user`
>> INNER JOIN `myapp_friendship` ON (`myapp_user`.`id` =
>> `myapp_friendship`.`friend_id`)
>> WHERE (`myapp_friendship`.`user_id` = 32
>>AND NOT ((`myapp_user`.`id` IN
>>(SELECT U1.`friend_id`
>> FROM `myapp_friendship` U1
>> WHERE (U1.`status` = 'pending'
>>AND U1.`friend_id` IS NOT NULL))
>>  AND `myapp_user`.`id` IS NOT NULL)))
>>
>>
>> Where clause should be as simple as:
>> `myapp_friendship`.`user_id` = 32 AND `myapp_friendship` != 'pending'
>>
>> Can someone shed some light? This kind of issue is appearing all over my
>> application.
>>
>  --
> You received this message because you are subscribed to a topic in the
> Google Groups

Re: Query friends of an user

2013-12-17 Thread C. Kirby
Why not just Friendship.objects.filter(user__pk = 32, status__in = 
[Friendship.FRIEND, Friendship.FAVORITE]) That will give you a QuerySet of 
all the friendships a user has. If you just want the list of friends then 
extend that query with a values_list like so:

Friendship.objects.filter(user__pk = 32, status__in = [Friendship.FRIEND, 
Friendship.FAVORITE]) .values_list('friend', flat=True)


On Tuesday, December 17, 2013 8:50:09 AM UTC-6, Arthur Silva wrote:
>
>  I want to query the friends of an User but I'm struggling to get the 
> correct query.
>
> Models:
>
> class User(AbstractUser, TimestampedModel, SerializeMixin):
> city = models.CharField(max_length=60, blank=True)
> picture = models.URLField(blank=True)
> cover_picture = models.URLField(blank=True)
> phone = models.CharField(max_length=20, blank=True)
> access_token = models.CharField(max_length=32, blank=True, null=True, 
> db_index=True)
> facebook_token = models.CharField(max_length=1024, blank=True, 
> null=True)
> facebook_id = models.BigIntegerField(blank=True, null=True, 
> db_index=True)
> twitter_token = models.CharField(max_length=1024, blank=True, 
> null=True)
> twitter_id = models.BigIntegerField(blank=True, null=True, unique=True)
> friends = models.ManyToManyField("self", through="Friendship", 
> symmetrical=False)
>
>
> class Friendship(TimestampedModel, SerializeMixin):
> PENDING = "pending"
> FRIEND = "friend"
> FAVORITE = "favorite"
> STATUS_CHOICES = (
> (PENDING, "Pending"),
> (FRIEND, "Friend"),
> (FAVORITE, "Favorite")
> )
> user = models.ForeignKey(User, related_name="friendships")
> friend = models.ForeignKey(User, related_name="friendships_reverse")
> status = models.CharField(max_length=20, default=PENDING, 
> choices=STATUS_CHOICES)
>
>
> Query I'm trying to make
>
> id = 32 # I want friends from this user
> friends = User.objects.extra(select={"friendship_status": 
> "status"}). \
> filter(Q(friendships_reverse__user_id=id), 
> ~Q(friendships_reverse__status=Friendship.PENDING))
>
>
> But the generated query is quite weird:
>
> SELECT (status) AS `friendship_status`,
>`myapp_user`.`id`,
>`myapp_user`.`password`,
>`myapp_user`.`last_login`,
>`myapp_user`.`is_superuser`,
>`myapp_user`.`username`,
>`myapp_user`.`first_name`,
>`myapp_user`.`last_name`,
>`myapp_user`.`email`,
>`myapp_user`.`is_staff`,
>`myapp_user`.`is_active`,
>`myapp_user`.`date_joined`,
>`myapp_user`.`created_at`,
>`myapp_user`.`updated_at`,
>`myapp_user`.`city`,
>`myapp_user`.`picture`,
>`myapp_user`.`cover_picture`,
>`myapp_user`.`phone`,
>`myapp_user`.`access_token`,
>`myapp_user`.`facebook_token`,
>`myapp_user`.`facebook_id`,
>`myapp_user`.`twitter_token`,
>`myapp_user`.`twitter_id`
> FROM `myapp_user`
> INNER JOIN `myapp_friendship` ON (`myapp_user`.`id` = 
> `myapp_friendship`.`friend_id`)
> WHERE (`myapp_friendship`.`user_id` = 32
>AND NOT ((`myapp_user`.`id` IN
>(SELECT U1.`friend_id`
> FROM `myapp_friendship` U1
> WHERE (U1.`status` = 'pending'
>AND U1.`friend_id` IS NOT NULL))
>  AND `myapp_user`.`id` IS NOT NULL)))
>
>
> Where clause should be as simple as:
> `myapp_friendship`.`user_id` = 32 AND `myapp_friendship` != 'pending' 
>
> Can someone shed some light? This kind of issue is appearing all over my 
> application.
>

-- 
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/4c0d9664-a4b7-41cc-bca0-e4055a1e0cc0%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Query friends of an user

2013-12-17 Thread Arthur Silva
 I want to query the friends of an User but I'm struggling to get the 
correct query.

Models:

class User(AbstractUser, TimestampedModel, SerializeMixin):
city = models.CharField(max_length=60, blank=True)
picture = models.URLField(blank=True)
cover_picture = models.URLField(blank=True)
phone = models.CharField(max_length=20, blank=True)
access_token = models.CharField(max_length=32, blank=True, null=True, 
db_index=True)
facebook_token = models.CharField(max_length=1024, blank=True, 
null=True)
facebook_id = models.BigIntegerField(blank=True, null=True, 
db_index=True)
twitter_token = models.CharField(max_length=1024, blank=True, null=True)
twitter_id = models.BigIntegerField(blank=True, null=True, unique=True)
friends = models.ManyToManyField("self", through="Friendship", 
symmetrical=False)


class Friendship(TimestampedModel, SerializeMixin):
PENDING = "pending"
FRIEND = "friend"
FAVORITE = "favorite"
STATUS_CHOICES = (
(PENDING, "Pending"),
(FRIEND, "Friend"),
(FAVORITE, "Favorite")
)
user = models.ForeignKey(User, related_name="friendships")
friend = models.ForeignKey(User, related_name="friendships_reverse")
status = models.CharField(max_length=20, default=PENDING, 
choices=STATUS_CHOICES)


Query I'm trying to make

id = 32 # I want friends from this user
friends = User.objects.extra(select={"friendship_status": 
"status"}). \
    filter(Q(friendships_reverse__user_id=id), 
~Q(friendships_reverse__status=Friendship.PENDING))


But the generated query is quite weird:

SELECT (status) AS `friendship_status`,
   `myapp_user`.`id`,
   `myapp_user`.`password`,
   `myapp_user`.`last_login`,
   `myapp_user`.`is_superuser`,
   `myapp_user`.`username`,
   `myapp_user`.`first_name`,
   `myapp_user`.`last_name`,
   `myapp_user`.`email`,
   `myapp_user`.`is_staff`,
   `myapp_user`.`is_active`,
   `myapp_user`.`date_joined`,
   `myapp_user`.`created_at`,
   `myapp_user`.`updated_at`,
   `myapp_user`.`city`,
   `myapp_user`.`picture`,
   `myapp_user`.`cover_picture`,
   `myapp_user`.`phone`,
   `myapp_user`.`access_token`,
   `myapp_user`.`facebook_token`,
   `myapp_user`.`facebook_id`,
   `myapp_user`.`twitter_token`,
   `myapp_user`.`twitter_id`
FROM `myapp_user`
INNER JOIN `myapp_friendship` ON (`myapp_user`.`id` = 
`myapp_friendship`.`friend_id`)
WHERE (`myapp_friendship`.`user_id` = 32
   AND NOT ((`myapp_user`.`id` IN
   (SELECT U1.`friend_id`
FROM `myapp_friendship` U1
WHERE (U1.`status` = 'pending'
   AND U1.`friend_id` IS NOT NULL))
 AND `myapp_user`.`id` IS NOT NULL)))


Where clause should be as simple as:
`myapp_friendship`.`user_id` = 32 AND `myapp_friendship` != 'pending' 

Can someone shed some light? This kind of issue is appearing all over my 
application.

-- 
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/9a418a08-9183-477f-a8fe-e848d200f022%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Adding Objects to Query Set

2013-12-17 Thread Vibhu Rishi
I will try this out also. Thanks!


On Tue, Dec 17, 2013 at 1:57 PM, Arnold Krille  wrote:

> Hi,
>
> define related names in ProjectMember:
>
> class ProjectMember(models.Model):
> project = models.ForeignKey(Project, related_name='members')
> member = models.ForeignKey(User)
> added_on = models.DateTimeField()
>
> The full query to get all Projects the User is either member or leader:
>
> Projects.objects.filter(
> Q(owner=user) | Q(members__member=user)
> )
>
> Don't merge in python what you can merge in the database. One
> query in the database is (almost) always faster then two queries and
> merging in python.
>
> Have fun,
>
> Arnold
>
> Am Mon, 16 Dec 2013 09:56:27 -0800 (PST)
> schrieb antialiasis :
> > Rather than fetching
> > ProjectMember.objects.filter(member=request.user), you want to fetch
> > Project.objects.filter(projectmember_set__member=request.user). That
> > will get you Project objects rather than ProjectMember objects.
> >
> > On Monday, December 16, 2013 1:47:13 PM UTC, Vibhu Rishi wrote:
> > >
> > > Hi
> > >
> > > I am not able to figure this out. I want to add objects to a query
> > > set.
> > >
> > > I have 2 models :
> > > 1. Projects which is basically a list of projects. I have a field
> > > which defines the owner of the project. e.g. :
> > >
> > > class Project(models.Model):
> > > ...
> > > owner = models.ForeignKey(User)
> > >
> > > 2. ProjectMember - This is a table where I add any user ( other
> > > than owner ) if they are member of the project.
> > >
> > > class ProjectMember(models.Model):
> > > project = models.ForeignKey(Project)
> > > member = models.ForeignKey(User)
> > > added_on = models.DateTimeField()
> > >
> > > What I am trying to do is get a list of projects which the current
> > > user is either owner or member of. So, I have this in my view :
> > >
> > > def mylist(request):
> > > projects = Project.objects.filter(owner=request.user)
> > > member_of = ProjectMember.objects.filter(member = request.user)
> > > # Now find all projects the user is a member of and add to the
> > > projects list
> > > all_projects = projects
> > > for m in member_of:
> > > all_projects |= m.project
> > > return render (request, "project/projects_mine.html",
> > > {'projects':projects})
> > >
> > >
> > > I am doing something wrong here as the line all_projects |=
> > > m.project is not working. I tried with a += also.
> > >
> > > How can I achieve what I am trying to do ?
> > >
> > > Vibhu
> > >
> > > --
> > > Simplicity is the ultimate sophistication. - Leonardo da Vinci
> > > Life is really simple, but we insist on making it complicated. -
> > > Confucius
> > >
> >
>
>


-- 
Simplicity is the ultimate sophistication. - Leonardo da Vinci
Life is really simple, but we insist on making it complicated. - Confucius

-- 
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/CAPiONwkrt35x43uEcdZkrsdm3N1FiA%3DEFww9rkGEB2G-P5RqoA%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Adding Objects to Query Set

2013-12-17 Thread Vibhu Rishi
This seems to be working with a slite modification. the _set was giving an
error. So, I changed to :

Project.objects.filter(projectmember__member=request.user)

I am not sure if that will just return 1 result or all the results. I have
to check that out.

Vibhu


On Mon, Dec 16, 2013 at 11:26 PM, antialiasis  wrote:

> Rather than fetching ProjectMember.objects.filter(member=request.user),
> you want to fetch
> Project.objects.filter(projectmember_set__member=request.user). That will
> get you Project objects rather than ProjectMember objects.
>
>
> On Monday, December 16, 2013 1:47:13 PM UTC, Vibhu Rishi wrote:
>>
>> Hi
>>
>> I am not able to figure this out. I want to add objects to a query set.
>>
>> I have 2 models :
>> 1. Projects which is basically a list of projects. I have a field which
>> defines the owner of the project. e.g. :
>>
>> class Project(models.Model):
>> ...
>> owner = models.ForeignKey(User)
>>
>> 2. ProjectMember - This is a table where I add any user ( other than
>> owner ) if they are member of the project.
>>
>> class ProjectMember(models.Model):
>> project = models.ForeignKey(Project)
>> member = models.ForeignKey(User)
>> added_on = models.DateTimeField()
>>
>> What I am trying to do is get a list of projects which the current user
>> is either owner or member of. So, I have this in my view :
>>
>> def mylist(request):
>> projects = Project.objects.filter(owner=request.user)
>> member_of = ProjectMember.objects.filter(member = request.user)
>> # Now find all projects the user is a member of and add to the
>> projects list
>> all_projects = projects
>> for m in member_of:
>> all_projects |= m.project
>> return render (request, "project/projects_mine.html",
>> {'projects':projects})
>>
>>
>> I am doing something wrong here as the line all_projects |= m.project is
>> not working. I tried with a += also.
>>
>> How can I achieve what I am trying to do ?
>>
>> Vibhu
>>
>> --
>> Simplicity is the ultimate sophistication. - Leonardo da Vinci
>> Life is really simple, but we insist on making it complicated. -
>> Confucius
>>
>  --
> 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/094848da-0d22-47a2-b97a-0abed22cc5e2%40googlegroups.com
> .
>
> For more options, visit https://groups.google.com/groups/opt_out.
>



-- 
Simplicity is the ultimate sophistication. - Leonardo da Vinci
Life is really simple, but we insist on making it complicated. - Confucius

-- 
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/CAPiONwkKd13THYjHH%2BTcQ27zgP2zOnyW%2BsYVAOQvC20WNXnhWg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Adding Objects to Query Set

2013-12-17 Thread Arnold Krille
Hi,

define related names in ProjectMember:

class ProjectMember(models.Model):
project = models.ForeignKey(Project, related_name='members')
member = models.ForeignKey(User)
added_on = models.DateTimeField()

The full query to get all Projects the User is either member or leader:

Projects.objects.filter(
Q(owner=user) | Q(members__member=user)
)

Don't merge in python what you can merge in the database. One
query in the database is (almost) always faster then two queries and
merging in python.

Have fun,

Arnold

Am Mon, 16 Dec 2013 09:56:27 -0800 (PST)
schrieb antialiasis :
> Rather than fetching
> ProjectMember.objects.filter(member=request.user), you want to fetch 
> Project.objects.filter(projectmember_set__member=request.user). That
> will get you Project objects rather than ProjectMember objects.
> 
> On Monday, December 16, 2013 1:47:13 PM UTC, Vibhu Rishi wrote:
> >
> > Hi 
> >
> > I am not able to figure this out. I want to add objects to a query
> > set. 
> >
> > I have 2 models :
> > 1. Projects which is basically a list of projects. I have a field
> > which defines the owner of the project. e.g. : 
> >
> > class Project(models.Model):
> > ...
> > owner = models.ForeignKey(User)
> >
> > 2. ProjectMember - This is a table where I add any user ( other
> > than owner ) if they are member of the project. 
> >
> > class ProjectMember(models.Model):
> > project = models.ForeignKey(Project)
> > member = models.ForeignKey(User)
> > added_on = models.DateTimeField()
> >
> > What I am trying to do is get a list of projects which the current
> > user is either owner or member of. So, I have this in my view : 
> >
> > def mylist(request):
> > projects = Project.objects.filter(owner=request.user)
> > member_of = ProjectMember.objects.filter(member = request.user)
> > # Now find all projects the user is a member of and add to the 
> > projects list
> > all_projects = projects
> > for m in member_of:
> > all_projects |= m.project
> > return render (request, "project/projects_mine.html", 
> > {'projects':projects})
> >  
> >
> > I am doing something wrong here as the line all_projects |=
> > m.project is not working. I tried with a += also. 
> >
> > How can I achieve what I am trying to do ? 
> >
> > Vibhu
> >
> > -- 
> > Simplicity is the ultimate sophistication. - Leonardo da Vinci
> > Life is really simple, but we insist on making it complicated. -
> > Confucius 
> >
> 



signature.asc
Description: PGP signature


Re: Adding Objects to Query Set

2013-12-16 Thread antialiasis
Rather than fetching ProjectMember.objects.filter(member=request.user), you 
want to fetch 
Project.objects.filter(projectmember_set__member=request.user). That will 
get you Project objects rather than ProjectMember objects.

On Monday, December 16, 2013 1:47:13 PM UTC, Vibhu Rishi wrote:
>
> Hi 
>
> I am not able to figure this out. I want to add objects to a query set. 
>
> I have 2 models :
> 1. Projects which is basically a list of projects. I have a field which 
> defines the owner of the project. e.g. : 
>
> class Project(models.Model):
> ...
> owner = models.ForeignKey(User)
>
> 2. ProjectMember - This is a table where I add any user ( other than owner 
> ) if they are member of the project. 
>
> class ProjectMember(models.Model):
> project = models.ForeignKey(Project)
> member = models.ForeignKey(User)
> added_on = models.DateTimeField()
>
> What I am trying to do is get a list of projects which the current user is 
> either owner or member of. So, I have this in my view : 
>
> def mylist(request):
> projects = Project.objects.filter(owner=request.user)
> member_of = ProjectMember.objects.filter(member = request.user)
> # Now find all projects the user is a member of and add to the 
> projects list
> all_projects = projects
> for m in member_of:
> all_projects |= m.project
> return render (request, "project/projects_mine.html", 
> {'projects':projects})
>  
>
> I am doing something wrong here as the line all_projects |= m.project is 
> not working. I tried with a += also. 
>
> How can I achieve what I am trying to do ? 
>
> Vibhu
>
> -- 
> Simplicity is the ultimate sophistication. - Leonardo da Vinci
> Life is really simple, but we insist on making it complicated. - Confucius 
>

-- 
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/094848da-0d22-47a2-b97a-0abed22cc5e2%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Adding Objects to Query Set

2013-12-16 Thread Vibhu Rishi
Hi Andrew,

The set seem to add on properly. How do i now access the project detail ?
When I try to iterate over it since this set is made of 2 different object
types, it fails for one of them.

e.g. i have in the project model attribute as 'name' for the project. so
when i iterate over the list like :

for o in totoal_projects:
  print o.name

this fails when it hits the ProjectMember objects as for them the name is
actually o.project.name

V.


On Mon, Dec 16, 2013 at 8:21 PM, Andrew Farrell wrote:

> It sounds like you just want a set of projects and don't actually need a
> querySet.
> You can do this with
> projects = set( Project.objects.filter(owner=request.user).all() )
> member_projects = set( ProjectMember.objects.filter(member = request.user)
> )
> total_projects = set(projects) | set(member_projects)
>
> You could also do
> projects = Project.objects.filter(owner=request.user).all()
> member_projects = ProjectMember.objects.filter(member =
> request.user).exclude(project__owner=request.user).all()
> total_projects = projects + member_projects
>
>
> On Mon, Dec 16, 2013 at 8:47 AM, Vibhu Rishi wrote:
>
>> Hi
>>
>> I am not able to figure this out. I want to add objects to a query set.
>>
>> I have 2 models :
>> 1. Projects which is basically a list of projects. I have a field which
>> defines the owner of the project. e.g. :
>>
>> class Project(models.Model):
>> ...
>> owner = models.ForeignKey(User)
>>
>> 2. ProjectMember - This is a table where I add any user ( other than
>> owner ) if they are member of the project.
>>
>> class ProjectMember(models.Model):
>> project = models.ForeignKey(Project)
>> member = models.ForeignKey(User)
>> added_on = models.DateTimeField()
>>
>> What I am trying to do is get a list of projects which the current user
>> is either owner or member of. So, I have this in my view :
>>
>> def mylist(request):
>> projects = Project.objects.filter(owner=request.user)
>> member_of = ProjectMember.objects.filter(member = request.user)
>> # Now find all projects the user is a member of and add to the
>> projects list
>> all_projects = projects
>> for m in member_of:
>> all_projects |= m.project
>> return render (request, "project/projects_mine.html",
>> {'projects':projects})
>>
>>
>> I am doing something wrong here as the line all_projects |= m.project is
>> not working. I tried with a += also.
>>
>> How can I achieve what I am trying to do ?
>>
>> Vibhu
>>
>> --
>> Simplicity is the ultimate sophistication. - Leonardo da Vinci
>> Life is really simple, but we insist on making it complicated. -
>> Confucius
>>
>> --
>> 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/CAPiONwm9%2Bnp_BROqjVEfmDaE_KgAnYnhv8u-GuiFBG7q2QeuaA%40mail.gmail.com
>> .
>>
>> 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.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CA%2By5TLaNBRwaYuRmJq1hzF2Lfb67dnOduu3%3D46_7TDX0TtRx%2Bw%40mail.gmail.com
> .
>
> For more options, visit https://groups.google.com/groups/opt_out.
>



-- 
Simplicity is the ultimate sophistication. - Leonardo da Vinci
Life is really simple, but we insist on making it complicated. - Confucius

-- 
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/CAPiONwkpAYipfg1n8MtwqLSjRuYKVG_cYmNArsC87o_3sUV_wQ%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Adding Objects to Query Set

2013-12-16 Thread Vibhu Rishi
Hi Sebastian,

Not really. I want the list of project objects which is coming ok by
filtering on the user object. I checked it from commandline, and I am
getting it correctly.

The problem is the 2nd table. I want to get the projects from the 1st table
when the user is a member as specified in the 2nd table.

e.g. following is the full list of projects. + denotes that I am owner. *
denotes where I am a member.

Project1
Project2 ( + )
Project 3
Project4 ( * )

When I do a projects = Project.objects.filter(owner=request.user) I get a
query set like :
[]

Now, when I do member_projects= Member.objects.filter(member=request.user)
I get a query set like:
[]

So far so good. I dont have any issues from them. However, in my templates,
now I need to pass on 2 querysets because these objects are different. I
have 2 loops for listing the projects. one for projects where I print the
name as  {{ o.name }} and one for the ProjectMember where I print the name
as o.project.name . I want to make the code neater and have just one loop :)

Now from the 2nd queryset ( since the object type is different), I want to
take out the actual project objects and add to the 1st set. Thats where I
am hitting a roadblock.

for o in member_projects
   o.project

works fine, as I get the project object.

However, now I want to add this project into the 1st queryset  - and there
i am not able to.

Hope this clears what I am trying to achieve!

V.

On Mon, Dec 16, 2013 at 8:21 PM, Sebastian Morkisch
wrote:

> Hi
>
> I am working on the same thing. Same here, one project model, one extended
> User model. Well, when I printed the request, I got the Usename, which is
> not an id, but you'd like to compare ids. Is that correct?
>
> So perhaps you're closer to a solution, if you have a method like this:
>
> def get_queryset(self):
>return Project.objects.filter(owner=self.request.user.id) <-- see that
> id?
>
> Best regards,
> Sebastian
>
>>  --
> 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/9dec582e-41c0-47b1-a9ed-65850eac8585%40googlegroups.com
> .
> For more options, visit https://groups.google.com/groups/opt_out.
>



-- 
Simplicity is the ultimate sophistication. - Leonardo da Vinci
Life is really simple, but we insist on making it complicated. - Confucius

-- 
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/CAPiONwka6BorE6ec8vRXgAy6X85HiCctZy55rR5MaetuzafSEw%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Adding Objects to Query Set

2013-12-16 Thread Andrew Farrell
It sounds like you just want a set of projects and don't actually need a
querySet.
You can do this with
projects = set( Project.objects.filter(owner=request.user).all() )
member_projects = set( ProjectMember.objects.filter(member = request.user) )
total_projects = set(projects) | set(member_projects)

You could also do
projects = Project.objects.filter(owner=request.user).all()
member_projects = ProjectMember.objects.filter(member =
request.user).exclude(project__owner=request.user).all()
total_projects = projects + member_projects


On Mon, Dec 16, 2013 at 8:47 AM, Vibhu Rishi  wrote:

> Hi
>
> I am not able to figure this out. I want to add objects to a query set.
>
> I have 2 models :
> 1. Projects which is basically a list of projects. I have a field which
> defines the owner of the project. e.g. :
>
> class Project(models.Model):
> ...
> owner = models.ForeignKey(User)
>
> 2. ProjectMember - This is a table where I add any user ( other than owner
> ) if they are member of the project.
>
> class ProjectMember(models.Model):
> project = models.ForeignKey(Project)
> member = models.ForeignKey(User)
> added_on = models.DateTimeField()
>
> What I am trying to do is get a list of projects which the current user is
> either owner or member of. So, I have this in my view :
>
> def mylist(request):
> projects = Project.objects.filter(owner=request.user)
> member_of = ProjectMember.objects.filter(member = request.user)
> # Now find all projects the user is a member of and add to the
> projects list
> all_projects = projects
> for m in member_of:
> all_projects |= m.project
> return render (request, "project/projects_mine.html",
> {'projects':projects})
>
>
> I am doing something wrong here as the line all_projects |= m.project is
> not working. I tried with a += also.
>
> How can I achieve what I am trying to do ?
>
> Vibhu
>
> --
> Simplicity is the ultimate sophistication. - Leonardo da Vinci
> Life is really simple, but we insist on making it complicated. - Confucius
>
> --
> 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/CAPiONwm9%2Bnp_BROqjVEfmDaE_KgAnYnhv8u-GuiFBG7q2QeuaA%40mail.gmail.com
> .
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2By5TLaNBRwaYuRmJq1hzF2Lfb67dnOduu3%3D46_7TDX0TtRx%2Bw%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Adding Objects to Query Set

2013-12-16 Thread Sebastian Morkisch
Hi

I am working on the same thing. Same here, one project model, one extended 
User model. Well, when I printed the request, I got the Usename, which is 
not an id, but you'd like to compare ids. Is that correct?

So perhaps you're closer to a solution, if you have a method like this:

def get_queryset(self):
   return Project.objects.filter(owner=self.request.user.id) <-- see that 
id?

Best regards,
Sebastian

>

-- 
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/9dec582e-41c0-47b1-a9ed-65850eac8585%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Adding Objects to Query Set

2013-12-16 Thread Vibhu Rishi
Hi

I am not able to figure this out. I want to add objects to a query set.

I have 2 models :
1. Projects which is basically a list of projects. I have a field which
defines the owner of the project. e.g. :

class Project(models.Model):
...
owner = models.ForeignKey(User)

2. ProjectMember - This is a table where I add any user ( other than owner
) if they are member of the project.

class ProjectMember(models.Model):
project = models.ForeignKey(Project)
member = models.ForeignKey(User)
added_on = models.DateTimeField()

What I am trying to do is get a list of projects which the current user is
either owner or member of. So, I have this in my view :

def mylist(request):
projects = Project.objects.filter(owner=request.user)
member_of = ProjectMember.objects.filter(member = request.user)
# Now find all projects the user is a member of and add to the projects
list
all_projects = projects
for m in member_of:
all_projects |= m.project
return render (request, "project/projects_mine.html",
{'projects':projects})


I am doing something wrong here as the line all_projects |= m.project is
not working. I tried with a += also.

How can I achieve what I am trying to do ?

Vibhu

-- 
Simplicity is the ultimate sophistication. - Leonardo da Vinci
Life is really simple, but we insist on making it complicated. - Confucius

-- 
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/CAPiONwm9%2Bnp_BROqjVEfmDaE_KgAnYnhv8u-GuiFBG7q2QeuaA%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: How to query multiple described objects exist in a many to many field

2013-12-05 Thread Aamu Padi
Thank you so much! That was a very helpful explanation. And it worked
perfectly!!!

Just, one more question please. Suppose, the user wants to send a message
to a group of users, how do I find the thread in this situation?

Eg: user1 wants to send a message to both the user2 and user3. How to find
the thread, in this case '*t3*'?

>>> t1 = Thread.objects.get(id=1)
>>> t1
[,]
>>> t2 = Thread.objects.get(id=2)
>>> t2
[,]
>>> t3 = Thread.objects.get(id=3)
>>> t3
[,,]


On Wed, Dec 4, 2013 at 5:41 PM, Tom Evans  wrote:

> On Wed, Dec 4, 2013 at 10:24 AM, Aamu Padi  wrote:
> > How do I check whether there is a thread containing only the sender
> (user 1)
> > and the recipient (user 2), and no other users.
> >
> > models.py
> >
> > class Thread(models.Model):
> > user = models.ManyToManyField(User)
> > is_hidden = models.ManyToManyField(User,
> > related_name='hidden_thread', blank=True)
> >
> > class Message(models.Model):
> > thread = models.ForeignKey(Thread)
> > sent_date = models.DateTimeField(default=datetime.now)
> > sender = models.ForeignKey(User)
> > body = models.TextField()
> > is_hidden = models.ManyToManyField(User,
> > related_name='hidden_message', blank=True)
> >
> > I tried
> >
> > >>> Thread.objects.filter(user=user1&user2)
> > >>> Thread.objects.filter(user=user1|user2)
> > # Both gave me an error:  Unsupported operand.
> >
> > # Then this
> > >>> Thread.objects.filter(Q(user=user1) & Q(user=user2))
> > # Which gave me no threads at all.
> >
> > # Then this
> > >>> Thread.objects.filter(Q(user=user1) | Q(user=user2)).distinct()
> > # Gave me threads of both the users.
> >
> > What I want is to check the thread, with the specified users only.
> Suppose,
> > User 1 wants to send a message to User 2. What I want is, first check
> > whether there is a thread between both the users. If there is, get that
> > thread, or else create a new one. How is it possible? What is the best
> way
> > to do it. Please help me. Thank you.
>
> I hope you understand SQL a little, as it will be required to follow
> this explanation.
>
> The condition "Thread.objects.filter(user=..)" goes across a join to
> the users<->threads "through" table, which has columns (id, thread_id,
> user_id).
>
> When you specify conditions in a "filter()" call, each of the
> conditions specified in that call is AND'ed together (the equivalent
> of what you were doing in the "Q(user=user1) & Q(user=user2)", django
> would do that for you). However, what does that mean, in terms of SQL?
>
> Well, it means "find me rows from the users<->threads through table
> that have user_id=user1.pk and user_id=user2.pk". Obviously, this will
> never find results unless user1==user2.
>
> So, you need to specify that you want to join twice to that table. You
> do this by specifying the conditions for each join in a separate
> "filter()" call, and so to find threads that have a row with user1 in
> the through table, and also have user2 in the through table:
>
> Thread.objects.filter(user=user1).filter(user=user2)
>
> You started by asking how to find threads which had user1 and user2,
> but no other users. This is more complex, you need to count the number
> of users in the thread without filtering the users first! This means
> two queries, or a sub query:
>
> threads_with_both = Thread.objects.filter(user=user1).filter(user=user2)
> threads_with_only_both = Thread.objects.filter(
>  pk__in=threads_with_both).annotate(
>  num_users=Count('user')).filter(
>  num_users=2)
>
> >
> > And please tell me what's the difference between | and &? Because I had
> very
> > different results with these two.
>
> | is OR
> & is AND
>
> So to find threads with either user1 or user2 (or both):
>
> Thread.objects.filter(Q(user=user1) | Q(user=user2))
>
> To find hidden threads with user1
>
> Thread.objects.filter(Q(user=user1) & Q(is_hidden=True))
>
> which is the same as
>
> Thread.objects.filter(user=user1, is_hidden=True)
>
>
> Cheers
>
> Tom
>
> --
> 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 

Re: How to query multiple described objects exist in a many to many field

2013-12-04 Thread Tom Evans
On Wed, Dec 4, 2013 at 10:24 AM, Aamu Padi  wrote:
> How do I check whether there is a thread containing only the sender (user 1)
> and the recipient (user 2), and no other users.
>
> models.py
>
> class Thread(models.Model):
> user = models.ManyToManyField(User)
> is_hidden = models.ManyToManyField(User,
> related_name='hidden_thread', blank=True)
>
> class Message(models.Model):
> thread = models.ForeignKey(Thread)
> sent_date = models.DateTimeField(default=datetime.now)
> sender = models.ForeignKey(User)
> body = models.TextField()
> is_hidden = models.ManyToManyField(User,
> related_name='hidden_message', blank=True)
>
> I tried
>
> >>> Thread.objects.filter(user=user1&user2)
> >>> Thread.objects.filter(user=user1|user2)
> # Both gave me an error:  Unsupported operand.
>
> # Then this
> >>> Thread.objects.filter(Q(user=user1) & Q(user=user2))
> # Which gave me no threads at all.
>
> # Then this
> >>> Thread.objects.filter(Q(user=user1) | Q(user=user2)).distinct()
> # Gave me threads of both the users.
>
> What I want is to check the thread, with the specified users only. Suppose,
> User 1 wants to send a message to User 2. What I want is, first check
> whether there is a thread between both the users. If there is, get that
> thread, or else create a new one. How is it possible? What is the best way
> to do it. Please help me. Thank you.

I hope you understand SQL a little, as it will be required to follow
this explanation.

The condition "Thread.objects.filter(user=..)" goes across a join to
the users<->threads "through" table, which has columns (id, thread_id,
user_id).

When you specify conditions in a "filter()" call, each of the
conditions specified in that call is AND'ed together (the equivalent
of what you were doing in the "Q(user=user1) & Q(user=user2)", django
would do that for you). However, what does that mean, in terms of SQL?

Well, it means "find me rows from the users<->threads through table
that have user_id=user1.pk and user_id=user2.pk". Obviously, this will
never find results unless user1==user2.

So, you need to specify that you want to join twice to that table. You
do this by specifying the conditions for each join in a separate
"filter()" call, and so to find threads that have a row with user1 in
the through table, and also have user2 in the through table:

Thread.objects.filter(user=user1).filter(user=user2)

You started by asking how to find threads which had user1 and user2,
but no other users. This is more complex, you need to count the number
of users in the thread without filtering the users first! This means
two queries, or a sub query:

threads_with_both = Thread.objects.filter(user=user1).filter(user=user2)
threads_with_only_both = Thread.objects.filter(
 pk__in=threads_with_both).annotate(
 num_users=Count('user')).filter(
 num_users=2)

>
> And please tell me what's the difference between | and &? Because I had very
> different results with these two.

| is OR
& is AND

So to find threads with either user1 or user2 (or both):

Thread.objects.filter(Q(user=user1) | Q(user=user2))

To find hidden threads with user1

Thread.objects.filter(Q(user=user1) & Q(is_hidden=True))

which is the same as

Thread.objects.filter(user=user1, is_hidden=True)


Cheers

Tom

-- 
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/CAFHbX1J%3DWX9p12B2X%2B1b_afDF0yEr80t0cfBsGbggzrKEBqqTg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


How to query multiple described objects exist in a many to many field

2013-12-04 Thread Aamu Padi
How do I check whether there is a thread containing only the sender (user
1) and the recipient (user 2), and no other users.

models.py

class Thread(models.Model):
user = models.ManyToManyField(User)
is_hidden = models.ManyToManyField(User,
related_name='hidden_thread', blank=True)

class Message(models.Model):
thread = models.ForeignKey(Thread)
sent_date = models.DateTimeField(default=datetime.now)
sender = models.ForeignKey(User)
body = models.TextField()
is_hidden = models.ManyToManyField(User,
related_name='hidden_message', blank=True)

I tried

>>> Thread.objects.filter(user=user1&user2)
>>> Thread.objects.filter(user=user1|user2)
# Both gave me an error:  Unsupported operand.

# Then this
>>> Thread.objects.filter(Q(user=user1) & Q(user=user2))
# Which gave me no threads at all.

# Then this
>>> Thread.objects.filter(Q(user=user1) | Q(user=user2)).distinct()
# Gave me threads of both the users.

What I want is to check the thread, with the specified users only. Suppose,
User 1 wants to send a message to User 2. What I want is, first check
whether there is a thread between both the users. If there is, get that
thread, or else create a new one. How is it possible? What is the best way
to do it. Please help me. Thank you.

And please tell me what's the difference between | and &? Because I had
very different results with these two.

-- 
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/CAHSNPWtFESu7WGZcHDOeNCVc1FqOqxqw2kkiRY0jaJctXy6XHQ%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Problem with raw query and using in

2013-11-19 Thread huw_at1
Hi,

I think I had something similar and followed this thread:

http://stackoverflow.com/questions/4574609/executing-select-where-in-using-mysqldb

I think this is what Dennis has already said so apologies if it isn't 
helpful.

Kindest regards

On Saturday, 16 November 2013 12:40:52 UTC, Thorsten wrote:
>
> Hello, 
>
> wondering if I am doing something wrong or it is a bug, using django 
> 1.5.5, but also tried with 1.6 resulting in the same problem. 
>
> When I do the following: 
>
> realms=[1] 
> data = AuctionData.objects.filter(itemid__exact=itemid,realm__in=realms) 
> data2 = AuctionData.objects.raw('SELECT * FROM auctiondata_auctiondata 
> WHERE itemid_id=%s AND realm_id in %s ',[itemid,realms]) 
>
> The first query works as expected, but the 2nd one fails, because the 
> query ends up as: 
>
> SELECT * FROM auctiondata_auctiondata WHERE itemid_id='43552' AND 
> realm_id in ('1',) 
>
> The last comma shouldnt be there, if I use more than 1 value with the 
> realms variable it works and the last comma isn't there. 
>
> Greetings, 
> Thorsten 
>
>

-- 
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/79829d6d-6f82-4de9-823d-8cbfb1cade7e%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Problem with raw query and using in

2013-11-17 Thread Thorsten Sanders
Thanks, I tried that, it makes the query right, but when I access the 
result in a for loop it gives now:


'Cursor' object has no attribute '_last_executed'

Think for now I just stay with using 2 variables, that works fine for 
the moment.



Am 17.11.2013 00:38, schrieb Dennis Lee Bieber:

On Sat, 16 Nov 2013 22:39:09 +0100, Thorsten Sanders
 declaimed the following:


I am using mysql and when I write it like (1) then I get int is not
iterable on the first one, but the raw works, if I do it like (1,) the
first one works, but the raw one gets again the comma at the end, tried
several ways always one of both not working, for me it looks kinda there
is some magic happening and with only 1 value the comma is not removed,
but is removed with several values.

For now I just use 2 variables one for the raw queries and one for the
other, not the best solution, but works for now.


Am 16.11.2013 16:01, schrieb Javier Guerra Giraldez:

On Sat, Nov 16, 2013 at 7:40 AM, Thorsten Sanders
 wrote:

realms=[1]
data = AuctionData.objects.filter(itemid__exact=itemid,realm__in=realms)
data2 = AuctionData.objects.raw('SELECT * FROM auctiondata_auctiondata WHERE
itemid_id=%s AND realm_id in %s ',[itemid,realms])

not sure if it's related. but most SQL adaptors use a tuple for the
IN(...) parameters, not a list.

check http://initd.org/psycopg/docs/usage.html#tuples-adaptation


I suspect the main problem is that you need to set up the realms
parameter differently -- along with the query string.

MySQL, and most other SQL systems, as I recall, expect to see

... needle in (first, second, ..., last)

MySQLdb sanitizes parameters by converting them to a string
representation, escaping any special characters, and wrapping it is '
marks.

In the raw query, unless Django has an SQL parser, the above is
generating

select * from auctiondata_auctiondata where itemid_id = 'something' and
realm_id in '[1]'

when what you need to generate is

select * from auctiondata_auctiondata where itemid_id = 'something' and
realm_id in ('1')

(MySQLdb doesn't know what datatype to put in at each %s -- it has first
converted all inputs into safe strings; that's why it uses %s for the
placeholder).

If using a list of values, you'll have to create an SQL format with a
%s for EACH value, not the list

SQL = " ...%%s and stuff in (%s)" % ", ".join("%s" for x in realms)
(if realms is [1, 3, 99] this creates   
SQL ="... %s stuff in (%s, %s, %s")

You then need to flatten the parameters

parms=[itemid].extend(realms)



--
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/5288A08E.4090605%40gmx.net.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Problem with raw query and using in

2013-11-16 Thread Thorsten Sanders
I am using mysql and when I write it like (1) then I get int is not 
iterable on the first one, but the raw works, if I do it like (1,) the 
first one works, but the raw one gets again the comma at the end, tried 
several ways always one of both not working, for me it looks kinda there 
is some magic happening and with only 1 value the comma is not removed, 
but is removed with several values.


For now I just use 2 variables one for the raw queries and one for the 
other, not the best solution, but works for now.



Am 16.11.2013 16:01, schrieb Javier Guerra Giraldez:

On Sat, Nov 16, 2013 at 7:40 AM, Thorsten Sanders
 wrote:

realms=[1]
data = AuctionData.objects.filter(itemid__exact=itemid,realm__in=realms)
data2 = AuctionData.objects.raw('SELECT * FROM auctiondata_auctiondata WHERE
itemid_id=%s AND realm_id in %s ',[itemid,realms])


not sure if it's related. but most SQL adaptors use a tuple for the
IN(...) parameters, not a list.

check http://initd.org/psycopg/docs/usage.html#tuples-adaptation



--
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/5287E5FD.4090406%40gmx.net.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Problem with raw query and using in

2013-11-16 Thread Javier Guerra Giraldez
On Sat, Nov 16, 2013 at 7:40 AM, Thorsten Sanders
 wrote:
> realms=[1]
> data = AuctionData.objects.filter(itemid__exact=itemid,realm__in=realms)
> data2 = AuctionData.objects.raw('SELECT * FROM auctiondata_auctiondata WHERE
> itemid_id=%s AND realm_id in %s ',[itemid,realms])


not sure if it's related. but most SQL adaptors use a tuple for the
IN(...) parameters, not a list.

check http://initd.org/psycopg/docs/usage.html#tuples-adaptation

-- 
Javier

-- 
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/CAFkDaoTSsD%2B8S0rdvOnHVCBxxF6UzRCK9jzscTW4Ff677Yt_dw%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Problem with raw query and using in

2013-11-16 Thread Thorsten Sanders

Hello,

wondering if I am doing something wrong or it is a bug, using django 
1.5.5, but also tried with 1.6 resulting in the same problem.


When I do the following:

realms=[1]
data = AuctionData.objects.filter(itemid__exact=itemid,realm__in=realms)
data2 = AuctionData.objects.raw('SELECT * FROM auctiondata_auctiondata 
WHERE itemid_id=%s AND realm_id in %s ',[itemid,realms])


The first query works as expected, but the 2nd one fails, because the 
query ends up as:


SELECT * FROM auctiondata_auctiondata WHERE itemid_id='43552' AND 
realm_id in ('1',)


The last comma shouldnt be there, if I use more than 1 value with the 
realms variable it works and the last comma isn't there.


Greetings,
Thorsten

--
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/528767D4.8080709%40gmx.net.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Is this what you would expect from this Q query?

2013-11-15 Thread Phoebe Bright
Aghh, the light has gone one.  The issue is in my models:


from django.db import models

from django.contrib.auth.models import User

class Carbon(models.Model):
user = models.ForeignKey(User, blank=True, null=True) <- 
 allowing null causes extra clause to be added in queryset
kg = models.DecimalField(max_digits=18, decimal_places=6, default=1)



To reproduce:

from web.models import *
from django.contrib.auth.models import User

u1=User.objects.create_user('A', 'a...@test.com', 'test')
u2=User.objects.create_user('B', 'b...@test.com', 'test')
u3=User.objects.create_user('C', 'c...@test.com', 'test')
u4=User.objects.create_user('D', 'd...@test.com', 'test')

Carbon.objects.create(user=u1, kg=10)
Carbon.objects.create(user=u2, kg=10)
Carbon.objects.create(user=u3, kg=10)
Carbon.objects.create(user=u4, kg=10)

rest = Carbon.objects.filter(~Q(user__in = 
[u1,u2,u3])).aggregate(total=Sum('kg'))

rest2 = Carbon.objects.exclude(user__in = 
[u1,u2,u3]).aggregate(total=Sum('kg'))


from django.db import connection
connection.queries

So simple in the end.

Thank you both for helping resolve this.  Will tighten up my model and 
remove option for a blank user.

Phoebe.


On Thursday, 14 November 2013 16:15:31 UTC, akaariai wrote:
>
> On Thursday, November 14, 2013 2:17:43 PM UTC+2, Phoebe Bright wrote:
>>
>> After a long time trying to create a simple version that would replicate 
>> the error, and failing, I've tracked it through the original code.
>>
>> Line 1140 in django/db/models/sql/query.py in function build_filter
>>
>> if current_negated and (lookup_type != 'isnull' or value is 
>> False):
>> self.promote_joins(join_list)
>> if (lookup_type != 'isnull' and (
>> self.is_nullable(targets[0]) or
>> self.alias_map[join_list[-1]].join_type == 
>> self.LOUTER)):
>> # The condition added here will be SQL like this:
>> # NOT (col IS NOT NULL), where the first NOT is added in
>> # upper layers of code. The reason for addition is that 
>> if col
>> # is null, then col != someval will result in SQL 
>> "unknown"
>> # which isn't the same as in Python. The Python None 
>> handling
>> # is wanted, and it can be gotten by
>> # (col IS NULL OR col != someval)
>> #   <=>
>> # NOT (col IS NOT NULL AND col = someval).
>> clause.add((Constraint(alias, targets[0].column, None), 
>> 'isnull', False), AND)  < this is adding the spurious clause
>>
>> This is django version 1.6 and happens using both the original Q version 
>> and using your suggested .exclude version.  
>> Having found it I'm still not sure what it means or how to avoid it being 
>> triggered!
>>
>> Any suggestions?
>>
>
> I believe the query is actually correct. The idea is that 
> .exclude(condition) produces complement of .filter(condition). The simplest 
> example I can generate is using raw SQL on PostgreSQL:
> akaariai=# create temp table foo(id integer);
> CREATE TABLE
> akaariai=# insert into foo values(null);
> INSERT 0 1
> -- What .filter(id__in=[1, 2, 3]) will do:
> akaariai=# select * from foo where id in (1, 2, 3);
>  id 
> 
> (0 rows)
>
> -- If the  "id is not null" condition isn't there
> akaariai=# select * from foo where not (id in (1, 2, 3));
>  id 
> 
> (0 rows)
>
> -- Note: we get still zero rows while we should get the complement, that 
> is one row.
> -- Add in the id is not null condition
> akaariai=# select * from foo where not (id in (1, 2, 3) and id is not 
> null);
>  id 
> 
>
> (1 row)
> -- Now we got the complement of the .filter() query.
>
> The problem comes from this feature in SQL:
>   NULL in (1, 2, 3) => unknown
>   NOT (NULL in (1, 2, 3)) => unknown
> so, NOT (condition) doesn't produce complement of (condition) in SQL! To 
> avoid that problem we have to add the AND id IS NOT NULL into the condition.
>
>  - Anssi
>

-- 
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/1cd0e599-67ff-4067-a23d-ed2d06017dac%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Is this what you would expect from this Q query?

2013-11-14 Thread akaariai
On Thursday, November 14, 2013 2:17:43 PM UTC+2, Phoebe Bright wrote:
>
> After a long time trying to create a simple version that would replicate 
> the error, and failing, I've tracked it through the original code.
>
> Line 1140 in django/db/models/sql/query.py in function build_filter
>
> if current_negated and (lookup_type != 'isnull' or value is False):
> self.promote_joins(join_list)
> if (lookup_type != 'isnull' and (
> self.is_nullable(targets[0]) or
> self.alias_map[join_list[-1]].join_type == 
> self.LOUTER)):
> # The condition added here will be SQL like this:
> # NOT (col IS NOT NULL), where the first NOT is added in
> # upper layers of code. The reason for addition is that if 
> col
> # is null, then col != someval will result in SQL "unknown"
> # which isn't the same as in Python. The Python None 
> handling
> # is wanted, and it can be gotten by
> # (col IS NULL OR col != someval)
> #   <=>
> # NOT (col IS NOT NULL AND col = someval).
> clause.add((Constraint(alias, targets[0].column, None), 
> 'isnull', False), AND)  < this is adding the spurious clause
>
> This is django version 1.6 and happens using both the original Q version 
> and using your suggested .exclude version.  
> Having found it I'm still not sure what it means or how to avoid it being 
> triggered!
>
> Any suggestions?
>

I believe the query is actually correct. The idea is that 
.exclude(condition) produces complement of .filter(condition). The simplest 
example I can generate is using raw SQL on PostgreSQL:
akaariai=# create temp table foo(id integer);
CREATE TABLE
akaariai=# insert into foo values(null);
INSERT 0 1
-- What .filter(id__in=[1, 2, 3]) will do:
akaariai=# select * from foo where id in (1, 2, 3);
 id 

(0 rows)

-- If the  "id is not null" condition isn't there
akaariai=# select * from foo where not (id in (1, 2, 3));
 id 

(0 rows)

-- Note: we get still zero rows while we should get the complement, that is 
one row.
-- Add in the id is not null condition
akaariai=# select * from foo where not (id in (1, 2, 3) and id is not null);
 id 

   
(1 row)
-- Now we got the complement of the .filter() query.

The problem comes from this feature in SQL:
  NULL in (1, 2, 3) => unknown
  NOT (NULL in (1, 2, 3)) => unknown
so, NOT (condition) doesn't produce complement of (condition) in SQL! To 
avoid that problem we have to add the AND id IS NOT NULL into the condition.

 - Anssi

-- 
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/133e9b0b-1e93-47fc-82ac-4a97d0cca021%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Is this what you would expect from this Q query?

2013-11-14 Thread tim
Please provide your models so I can reproduce it myself. It's quite 
difficult (at least for me) to help otherwise.

On Thursday, November 14, 2013 7:17:43 AM UTC-5, Phoebe Bright wrote:
>
> After a long time trying to create a simple version that would replicate 
> the error, and failing, I've tracked it through the original code.
>
> Line 1140 in django/db/models/sql/query.py in function build_filter
>
> if current_negated and (lookup_type != 'isnull' or value is False):
> self.promote_joins(join_list)
> if (lookup_type != 'isnull' and (
> self.is_nullable(targets[0]) or
> self.alias_map[join_list[-1]].join_type == 
> self.LOUTER)):
> # The condition added here will be SQL like this:
> # NOT (col IS NOT NULL), where the first NOT is added in
> # upper layers of code. The reason for addition is that if 
> col
> # is null, then col != someval will result in SQL "unknown"
> # which isn't the same as in Python. The Python None 
> handling
> # is wanted, and it can be gotten by
> # (col IS NULL OR col != someval)
> #   <=>
> # NOT (col IS NOT NULL AND col = someval).
> clause.add((Constraint(alias, targets[0].column, None), 
> 'isnull', False), AND)  < this is adding the spurious clause
>
> This is django version 1.6 and happens using both the original Q version 
> and using your suggested .exclude version.  
> Having found it I'm still not sure what it means or how to avoid it being 
> triggered!
>
> Any suggestions?
>
> Phoebe.
>
>
>

-- 
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/389a4a4e-86ae-4bfe-82a9-57436238462c%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Is this what you would expect from this Q query?

2013-11-14 Thread Phoebe Bright
After a long time trying to create a simple version that would replicate 
the error, and failing, I've tracked it through the original code.

Line 1140 in django/db/models/sql/query.py in function build_filter

if current_negated and (lookup_type != 'isnull' or value is False):
self.promote_joins(join_list)
if (lookup_type != 'isnull' and (
self.is_nullable(targets[0]) or
self.alias_map[join_list[-1]].join_type == 
self.LOUTER)):
# The condition added here will be SQL like this:
# NOT (col IS NOT NULL), where the first NOT is added in
# upper layers of code. The reason for addition is that if 
col
# is null, then col != someval will result in SQL "unknown"
# which isn't the same as in Python. The Python None 
handling
# is wanted, and it can be gotten by
# (col IS NULL OR col != someval)
#   <=>
# NOT (col IS NOT NULL AND col = someval).
clause.add((Constraint(alias, targets[0].column, None), 
'isnull', False), AND)  < this is adding the spurious clause

This is django version 1.6 and happens using both the original Q version 
and using your suggested .exclude version.  
Having found it I'm still not sure what it means or how to avoid it being 
triggered!

Any suggestions?

Phoebe.


-- 
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/716b0373-8975-4518-815d-88906fb188db%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Is this what you would expect from this Q query?

2013-11-13 Thread tim
Hi Phoebe,

I cannot reproduce this on Django's master branch. What version of Django 
are you using? It's possible it was fixed since then. Could you provide a 
minimal set of models to reproduce?

If upgrading to a more recent version of Djanago doesn't fix the problem, 
you might try .exclude(user__in= rather than .filter(~Q if that works for 
your query.

Tim

On Monday, November 11, 2013 6:36:12 AM UTC-5, Phoebe Bright wrote:
>
> I have this line in my code where the functions return an ID and what I 
> wanted was to select all records that did not belong to one of these users.
>
> Carbon.objects.filter(~Q(user__in = [limbo_user(), system_user(), 
> retire_user()]))
>
> What I expected to get was 
>
> *SELECT* ••• <http://127.0.0.1:8000/dash/#> *FROM* "web_carbon" *WHERE* 
> *NOT*(("web_carbon"."user_id" *IN* (5, 2, 4))
>
> but what I actually got was
>
> *SELECT* ••• <http://127.0.0.1:8000/dash/#> *FROM* "web_carbon" *WHERE* 
> *NOT*(("web_carbon"."user_id" *IN* (5, 2, 4) *AND* "web_carbon"."user_id" 
> *IS**NOT NULL*)) 
>
> So it always returns a null set.  Is this correct behaviour and if so, 
> does anyone know what the correct syntax is?
>

-- 
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/be576720-2ccd-4123-bfc4-1a2e45acb8eb%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Is this what you would expect from this Q query?

2013-11-11 Thread Phoebe Bright
I have this line in my code where the functions return an ID and what I 
wanted was to select all records that did not belong to one of these users.

Carbon.objects.filter(~Q(user__in = [limbo_user(), system_user(), 
retire_user()]))

What I expected to get was 

*SELECT* •••  *FROM* "web_carbon" *WHERE* 
*NOT*(("web_carbon"."user_id" *IN* (5, 2, 4))

but what I actually got was

*SELECT* •••  *FROM* "web_carbon" *WHERE* 
*NOT*(("web_carbon"."user_id" *IN* (5, 2, 4) *AND* "web_carbon"."user_id" 
*IS**NOT NULL*)) 

So it always returns a null set.  Is this correct behaviour and if so, does 
anyone know what the correct syntax is?

-- 
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/012666c4-3fba-4fef-b8e8-55d27f06a895%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Complex query reduction

2013-11-08 Thread Javier Guerra Giraldez
On Fri, Nov 8, 2013 at 1:44 AM, Robin St.Clair  wrote:
> The last time I checked the use of IN, all the records from the database in
> the query were brought back to the workstation, rather than being processed
> on the backend and only the results returned to the workstation.


Django ORM's __in operator tries to use SQL facilities, but depending
on the type of object passed, it could read the list of options and
pass it explicitly, or it could merge two SQL commands.  always check
the type of SQL commands generated!  (debug toolbar is your friend)

i haven't seen it doing a post-retrieve check in python, thought.

-- 
Javier

-- 
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/CAFkDaoRLfeLi%3DWVu5f%3DcyCXRH0x5mr1fbDiV0OzW%2Bn-fpk6uHw%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Complex query reduction

2013-11-08 Thread François Schiettecatte
I am pretty sure the IN() performance issue in MySQL was fixed 5.5, and  
5.6/5.7 certainly don't have an issue with IN() whether you use a bunch of 
values or a subquery.

Cheers

François

On Nov 8, 2013, at 2:15 AM, akaariai  wrote:

> On Friday, November 8, 2013 8:44:09 AM UTC+2, Robin St.Clair wrote:
> Anssi
> 
> The last time I checked the use of IN, all the records from the database in 
> the query were brought back to the workstation, rather than being processed 
> on the backend and only the results returned to the workstation.
> 
> Have there been changes that carry out the entire query on the backend? What 
> has changed to cause you to prefer the use of the IN statement?
> 
> Django has had the ability to execute __in=qs in single query for a somewhat 
> long time (from Django 1.2 maybe?).
> 
> It is true that __in lookup against a large list of values is often a bad 
> choice even if you have the values at hand. Unfortunately this doesn't apply 
> to all databases, for example older versions of MySQL do not handle 
> subqueries well.
> 
>  - Anssi
> 
> -- 
> 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/f3428fda-e4be-4d75-8626-a95bd20f66c8%40googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.



signature.asc
Description: Message signed with OpenPGP using GPGMail


Re: Complex query reduction

2013-11-07 Thread akaariai
On Friday, November 8, 2013 8:44:09 AM UTC+2, Robin St.Clair wrote:
>
>  Anssi
>
> The last time I checked the use of IN, all the records from the database 
> in the query were brought back to the workstation, rather than being 
> processed on the backend and only the results returned to the workstation.
>
> Have there been changes that carry out the entire query on the backend? 
> What has changed to cause you to prefer the use of the IN statement?
>

Django has had the ability to execute __in=qs in single query for a 
somewhat long time (from Django 1.2 maybe?).

It is true that __in lookup against a large list of values is often a bad 
choice even if you have the values at hand. Unfortunately this doesn't 
apply to all databases, for example older versions of MySQL do not handle 
subqueries well.

 - Anssi

-- 
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/f3428fda-e4be-4d75-8626-a95bd20f66c8%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Complex query reduction

2013-11-07 Thread Robin St . Clair

Anssi

The last time I checked the use of IN, all the records from the database 
in the query were brought back to the workstation, rather than being 
processed on the backend and only the results returned to the workstation.


Have there been changes that carry out the entire query on the backend? 
What has changed to cause you to prefer the use of the IN statement?


R+C
On 08/11/2013 05:55, akaariai wrote:

On Sunday, November 3, 2013 1:48:07 PM UTC+2, Robin St.Clair wrote:

*IN*

  * if using Django avoid the IN operation at all costs


If there are potentially more than 15 items in the list, rework
the IN as a JOIN against whatever the source of the keys is


I don't necessarily agree with everything else said in the post, but 
this one is just plain wrong. It is completely OK to use 
__in=queryset. In fact, it is recommended in cases where the alternate 
is using join + distinct.


 - Anssi
--
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/6b5f9e3a-2e41-47b5-b0d6-94473fe323b8%40googlegroups.com.

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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/BLU0-SMTP357C2324CC6BEC3F975EB4AE2F20%40phx.gbl.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Complex query reduction

2013-11-07 Thread akaariai
On Sunday, November 3, 2013 1:48:07 PM UTC+2, Robin St.Clair wrote:
>
> *IN*
>
>- if using Django avoid the IN operation at all costs
>
>
> If there are potentially more than 15 items in the list, rework the IN as 
> a JOIN against whatever the source of the keys is
>

I don't necessarily agree with everything else said in the post, but this 
one is just plain wrong. It is completely OK to use __in=queryset. In fact, 
it is recommended in cases where the alternate is using join + distinct.

 - Anssi 

-- 
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/6b5f9e3a-2e41-47b5-b0d6-94473fe323b8%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Complex query reduction

2013-11-04 Thread Apostolos Bessas
On Sat, Nov 2, 2013 at 4:50 PM, Daniele Procida  wrote:
>
> But, the real killer is the combination of ordering (in the queryset or on 
> the model, it doesn't matter) with the distinct() - as soon as one is removed 
> from the equation, the execution time drops to around 250ms.
>
> That's for 55000 BibliographicRecords created by that last operation (before 
> distinct() is applied; distinct() reduces them to 28000).


Do you happen to use PostgreSQL? This could be a case of a
"non-optimal" configuration, that makes PostgreSQL use the disk to do
the sorting. Take a look at
http://www.postgresql.org/docs/current/static/runtime-config-resource.html#GUC-WORK-MEM.

Apostolis

-- 
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/CAEa3b%2BoCFp3oPwtcR-uyoERW3YwHR4aXLubp7WUpa%2BHtYNhvmw%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


RE: Complex query reduction

2013-11-03 Thread Robin St . Clair
Hi
You are running into typical production Django problems - works fine in 
testing, terrible in production.
Firstly
If you use attributed many-to-manys, create the table outside of Django and use 
raw SQL.Create a primary key on the two things being related (usually larger 
table first).
Multi-column indicesTwo choicesA single index that includes both (do this 
outside Django)Two indices, one for each columnThe size will be roughly 
equivalent between the two
Single composite indexsmaller than two indexes.faster to update.accelerates a 
more restricted range of queries.An index on (A, B) does nothing for queries 
just using BBut on the queries it does accelerate, it will be faster.
Two indiceslargerslower to updatewill help on queries on both columns, but not 
as much as a single composite indexwill help accelerate queries on either of 
the columnscan be expressed directly in Django
Helpful Toolpg_stat_activity shows a wealth of useful information - including
which indexes are actually being used
If an index is not being used (or not being used very often) drop itif you are 
surprised that it is not being used, find out why
Basic Performance Rules1. Do not iterate over QuerySets2. If you think you have 
to iterate over a QuerySet, see rule #13. If you are absolutely, certainly, 
100% positive that the only possible solution to your problem is iterating over 
a QuerySet, see rule #3
Iteration - A Health Warning• Ignores Django’s lazy-evaluation mechanism and 
copies everything into local memory• Copies data from the database just to 
process it locally• Does filtration or summation in the application that is 
processed more efficiently in the database.• Databases are good at this sort of 
stuff let the DB do it
Alternatives to Iteration• QuerySet.update()• cursor.execute(“UPDATE 
reader_hours ...”)• Stored procedures
Take in the code below
How much many objects are in memory at point A?
qs = Orders.objects.all() # There are about 2,500,000 rows in “orders”
for order in qs:order.age_in_days += 1 # POINT A order.save()
Answer  - 2,500,000
Why Is This?
Django does lazy evaluation… (everyone tells me so!)The Django code carefully 
asks for a slice of 100 objectswhich trickles down through lots of really 
convoluted Python to psycopg2which dutifully asks for 100 rows from 
Postgreswhich sends all 2,500,000 over the wire
Solution - Named CursorsThe protocol between the Postgres client and server 
only does partial sends when using named cursorspsycopg2 fully supports named 
cursorsDjango doesn’t use named cursorsTherefore, the first time you ask for any 
object in a QuerySet, you get all of themThis is a very good reason not to ask 
for large result sets
INif using Django avoid the IN operation at all costs
If there are potentially more than 15 items in the list, rework the IN as a 
JOIN against whatever the source of the keys is

At some stage you are going to have to get to grips with SQL, might as well be 
sooner than later
R+C
PS some time ago one of my clients was only able to process 4 transactons a 
second against their very complicated DB. They needed to process 70+ 
transactions per second. After 3 days of code analysis we had the transaction 
rate up to 240 per second and so could get rid of the 6 week backlog that had 
developed. Front end coders didn't consider the DBMS to be importantDate: Sun, 
3 Nov 2013 02:37:09 -0800
From: akaar...@gmail.com
To: django-users@googlegroups.com
Subject: Re: Complex query reduction

You should rewrite the query into a form that doesn't require distinct. In 
general, when you see a query that has joins and DISTINCT, that should be an 
alarm bell that something isn't written correctly in the query. Unfortunately 
Django's ORM generates such queries, and that isn't easy to fix as there are 
databases that like DISTINCT more than rewriting the query to use subqueries.

In any case, you should check how to write the query without the need of 
distinct. Something like this should work:

self.items = BibliographicRecord.objects.listable_objects().filter(

authored__researcher__in=researchers,

)

self.items = BibliographicRecord.objects.listable_objects().filter(

pk__in=self.items.values_list('pk')

)

But maybe you can push the __in to deeper into the authored__researches 
lookup...

 - Anssi

On Saturday, November 2, 2013 4:50:42 PM UTC+2, Daniele Procida wrote:On Fri, 
Nov 1, 2013, Javier Guerra Giraldez  wrote:



>have you tried eliminating the second IN relationship?  something like

>

>entities = entity.get_descendants()

>

>items = BibliographicRecord.objects.filter

>(authored__researcher__person__member_of__entity__in=entities).distinct()



Indeed I have, but in that form it takes around 1770ms, compared to around 
1540ms in the original form. What I actually do is:



# breaking apart the queries allows the use of values_lists

entities = self.entity.get_descendants(

Re: Complex query reduction

2013-11-03 Thread akaariai
You should rewrite the query into a form that doesn't require distinct. In 
general, when you see a query that has joins and DISTINCT, that should be 
an alarm bell that something isn't written correctly in the query. 
Unfortunately Django's ORM generates such queries, and that isn't easy to 
fix as there are databases that like DISTINCT more than rewriting the query 
to use subqueries.

In any case, you should check how to write the query without the need of 
distinct. Something like this should work:

self.items = BibliographicRecord.objects.
listable_objects().filter( 
authored__researcher__in=researchers, 
)
self.items = BibliographicRecord.objects.
listable_objects().filter( 
pk__in=self.items.values_list('pk') 
)

But maybe you can push the __in to deeper into the authored__researches 
lookup...

 - Anssi

On Saturday, November 2, 2013 4:50:42 PM UTC+2, Daniele Procida wrote:
>
> On Fri, Nov 1, 2013, Javier Guerra Giraldez > 
> wrote: 
>
> >have you tried eliminating the second IN relationship?  something like 
> > 
> >entities = entity.get_descendants() 
> > 
> >items = BibliographicRecord.objects.filter 
> >(authored__researcher__person__member_of__entity__in=entities).distinct() 
>
> Indeed I have, but in that form it takes around 1770ms, compared to around 
> 1540ms in the original form. What I actually do is: 
>
> # breaking apart the queries allows the use of values_lists 
> entities = self.entity.get_descendants( 
> include_self=True 
> ).values_list('id', flat=True) 
>
> # and the set() here is about 230ms faster than putting a distinct() 
> on 
> # the first query 
> researchers = set(Researcher.objects.filter( 
> person__entities__in=entities 
> ).values_list('person', flat=True)) 
>
> self.items = BibliographicRecord.objects.listable_objects().filter( 
> authored__researcher__in=researchers, 
> ).distinct() 
>
> I think that's partly because this way the SELECT doesn't have to grab all 
> the fields of publications_bibliographicrecord. 
>
> But, the real killer is the combination of ordering (in the queryset or on 
> the model, it doesn't matter) with the distinct() - as soon as one is 
> removed from the equation, the execution time drops to around 250ms. 
>
> That's for 55000 BibliographicRecords created by that last operation 
> (before distinct() is applied; distinct() reduces them to 28000). 
>
> That seems excessive to me. 
>
> BibliographicRecord has a custom primary key, and its id fields look like 
> "d9ce7e2f-663e-4fc6-8448-b214c6915aed:web-of-science". Could that be 
> implicated in performance? 
>
> Daniele 
>
>

-- 
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/8208cc22-cc94-4fe6-9245-709bdc42647f%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Complex query reduction

2013-11-02 Thread Daniele Procida
On Fri, Nov 1, 2013, Javier Guerra Giraldez  wrote:

>have you tried eliminating the second IN relationship?  something like
>
>entities = entity.get_descendants()
>
>items = BibliographicRecord.objects.filter
>(authored__researcher__person__member_of__entity__in=entities).distinct()

Indeed I have, but in that form it takes around 1770ms, compared to around 
1540ms in the original form. What I actually do is:

# breaking apart the queries allows the use of values_lists
entities = self.entity.get_descendants(
include_self=True
).values_list('id', flat=True)

# and the set() here is about 230ms faster than putting a distinct() on 
# the first query
researchers = set(Researcher.objects.filter(
person__entities__in=entities
).values_list('person', flat=True))

self.items = BibliographicRecord.objects.listable_objects().filter(
authored__researcher__in=researchers,
).distinct()

I think that's partly because this way the SELECT doesn't have to grab all the 
fields of publications_bibliographicrecord.

But, the real killer is the combination of ordering (in the queryset or on the 
model, it doesn't matter) with the distinct() - as soon as one is removed from 
the equation, the execution time drops to around 250ms.

That's for 55000 BibliographicRecords created by that last operation (before 
distinct() is applied; distinct() reduces them to 28000).

That seems excessive to me. 

BibliographicRecord has a custom primary key, and its id fields look like 
"d9ce7e2f-663e-4fc6-8448-b214c6915aed:web-of-science". Could that be implicated 
in performance?

Daniele

-- 
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/20131102145042.868061817%40smtp.modern-world.net.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Complex query reduction

2013-11-01 Thread Javier Guerra Giraldez
On Fri, Nov 1, 2013 at 12:45 PM, Daniele Procida  wrote:
> In practice I use some tweaks (such as values_list) to speed this up, and 
> caching, but the fundamental pattern is the same. It's slow, because there 
> are 30 thousand BibliographicRecords.


the total number of records shouldn't matter.  more important is the
number of selected records at some points in the query.  i'd guess the
number of chosen entities (those that _are_ descendant of the first
one), and the number of chosen researches (those that _are_ members of
those entities) should be the most significant quantities.

the point is that most DB optimizers are somewhat shy to shuffle
conditions around IN operators.  but it might be easier to work on a
small (a few tens of values?) IN condition than on a very long JOIN
chain.

>
> I'm trying to rearrange the construction of the query in different ways to 
> find a speed improvement. I don't think that either prefetch_related or 
> select_related will help here, but perhaps there are some other tools that 
> would.


have you tried eliminating the second IN relationship?  something like

entities = entity.get_descendants()

items = 
BibliographicRecord.objects.filter(authored__researcher__person__member_of__entity__in=entities).distinct()

that should turn most of the query in a long sequence of "INNER JOIN",
giving the optimizer an easier job, avoiding the IN operation on
research records.  if the query chooses too many researches, this
could be a big part of the slowness.

-- 
Javier

-- 
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/CAFkDaoSVg3K44wRUnOTrinqXZbVKm1ZZLHxFPB8LdgrzBtxViA%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Complex query reduction

2013-11-01 Thread Daniele Procida
I have been exploring a rather complex query:

# get all the MPTT descendants of entity
entities = entity.get_descendants()
 
# get all the Researchers in these Entities
researchers = Researcher.objects.filter(person__member_of__entity__in=entities)
 
# get all the BibliographicRecords for these Researchers
items = 
BibliographicRecord.objects.filter(authored__researcher__in=researchers).distinct()

In practice I use some tweaks (such as values_list) to speed this up, and 
caching, but the fundamental pattern is the same. It's slow, because there are 
30 thousand BibliographicRecords.

I'm trying to rearrange the construction of the query in different ways to find 
a speed improvement. I don't think that either prefetch_related or 
select_related will help here, but perhaps there are some other tools that 
would.

Any suggestions?

At <https://dpaste.de/8vwP> I've shown the SQL generated, and the models being 
used.

Thanks,

Daniele

-- 
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/20131101174524.207157947%40smtp.modern-world.net.
For more options, visit https://groups.google.com/groups/opt_out.


Dynamic query with Foreign Key

2013-10-30 Thread Domagoj Kovač
Hi guys,

I have a question. I have a a code like this: 

where model_object is an instance of an Model.

for field in model_object._meta.fields:
field_type = type(field)
if field_type is not AutoField and \
field.name != "created" and \
field.name != "created_by" and \
field.name != "modified" and \
field.name != "modified_by" and \
field.name != "deleted" and \
field.name != "deleted_by":
q = None
if field_type is CharField:
q = Q(**{"%s__contains" % field.name: search_term })
elif field_type is ForeignKey:
q = Q(**{"%s__name__contains" % field.name: search_term 
})

        if q:
if query:
    query = query | q
    else:
query = q

rows_list = rows_list.filter(query)


I would like to create a function that i can use for searching trough 
database. The problem is that i want to be able to search trough Foreign 
Key fields. Models have __unicode__, is there any way that i could search 
trough the value defined in __unicode__?

-- 
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/028ab892-1f80-4dcf-9972-24dca90ffc5c%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Django ORM generating the wrong query for recent friends of an user

2013-10-16 Thread Arthur Silva
I still can't find the problem.  Django isn't using the same "friendship" 
joined table for both conditions which makes me wonder if it's related to 
this 
https://docs.djangoproject.com/en/1.5/topics/db/queries/#spanning-multi-valued-relationships

Please help.

On Tuesday, September 24, 2013 10:50:54 AM UTC-3, Arthur Silva wrote:
>
> Here're my models
>
>
> class PingUser(AbstractUser):
> friends = models.ManyToManyField("self", through="Friendship", 
> symmetrical=False)
> 
> class Friendship(TimestampedModel, SerializeMixin):
> STATUS_CHOICES = (
> ("pending", "Pending"),
> ("friend", "Friend"),
> ("favorite", "Favorite")
> )
> user = models.ForeignKey(PingUser, related_name="friendships")
> friend = models.ForeignKey(PingUser, 
> related_name="friendships_reverse")
> status = models.CharField(max_length=20, 
> default=STATUS_CHOICES[0][0], choices=STATUS_CHOICES)
>
> class Meta:
> unique_together = [('user', 'friend')]
>
>
>
> The code I'm using to get the most recent friends of user 4
>
>
> id = 4
> friendships = Friendship.objects.exclude(status="pending").filter(
> ~Q(user__friendships__status="pending"), 
> user__friendships__friend_id=id).order_by("-created_at")
>
>
> I also tried several combinations like grouping all filtering inside one 
> filter() but the query is the same
>
>
> Generated query
>
>
> SELECT `sample_app_friendship`.`id`,
>`sample_app_friendship`.`created_at`,
>`sample_app_friendship`.`updated_at`,
>`sample_app_friendship`.`user_id`,
>`sample_app_friendship`.`friend_id`,
>`sample_app_friendship`.`status`
> FROM `sample_app_friendship`
> INNER JOIN `sample_app_pinguser` ON (`sample_app_friendship`.`user_id` 
> = `sample_app_pinguser`.`id`)
> INNER JOIN `sample_app_friendship` T5 ON (`sample_app_pinguser`.`id` = 
> T5.`user_id`)
> WHERE (NOT (`sample_app_friendship`.`status` = 'pending')
>AND NOT ((`sample_app_friendship`.`user_id` IN
>(SELECT U2.`user_id`
> FROM `sample_app_friendship` U2
> WHERE (U2.`status` = 'pending'
>AND U2.`user_id` IS NOT NULL))
>  AND `sample_app_pinguser`.`id` IS NOT NULL))
>AND T5.`friend_id` = 4)
>
>
>
> The desired query is actually
>
>
> SELECT `sample_app_friendship`.`id`,
>`sample_app_friendship`.`created_at`,
>`sample_app_friendship`.`updated_at`,
>`sample_app_friendship`.`user_id`,
>`sample_app_friendship`.`friend_id`,
>`sample_app_friendship`.`status`
> FROM `sample_app_friendship`
> INNER JOIN `sample_app_pinguser` ON (`sample_app_friendship`.`user_id` 
> = `sample_app_pinguser`.`id`)
> INNER JOIN `sample_app_friendship` T5 ON (`sample_app_pinguser`.`id` = 
> T5.`user_id`)
> WHERE (NOT (`sample_app_friendship`.`status` = 'pending')
>AND (NOT T5.`status` = 'pending')
>AND T5.`friend_id` = 4)
>
> Someone more experienced can shed some light?
>
> Thanks!
>
>

-- 
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/e38830e9-51a6-4ed2-afa9-dc2b44c8110f%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Django query from database

2013-10-11 Thread Leonardo Giordani
Ok, I think I got the point.

So, correct me if I didn't get it right, you have to get users which have
first_name, last_name, or other fields equal to the words in your list B.

This can be accomplished by looking at each field for each keyword. I would
also compile a dictionary keeping reference of what field matches the search
Continuing the code I wrote above:

users = {}
for field in ['first_name', 'last_name']:
# build something like {'first_name__in', ['David', 'Henry', 'Ostro', '
Henroo']}
filter_dict = {field + '__in': B}

# find all users that match
results = User.objects.filter(**filter_dict)

# store each user and the list of its fields that match the search
for user in results:
try:
   users[user].append(field)
except KeyError:
users[user] = [field]

This is perhaps the worst Python code I ever wrote, but I hope you can
tolerate it. Also beware that it is written directly in the mail composer
(so indentation is wrong and code is untested).

Now I realize that the "__in" trick can be used also for the first code I
wrote, try it.

As for the template, you can pass the users dict in the context. In the
template loop over the key/values with

{% for user,fields in users.iteritems %}
{% endfor %}

inside this loop you can further loop over fields with

{% for field in fields %}
{% endfor %}

I am not sure if inside this last loop you can write something like

{{ user.field }}

since I have to check if the template attribute retrieving syntax also
performs getattr. if this does not work you have to store tuples as values
of the users dict, instead of fields, each tuple being (field,
getattr(user, field)).

Try to give a sense to all this stuff and let me know!

Cheers,
Leo



Leonardo Giordani
Author of The Digital Cat 
My profile on About.me  - My GitHub
page- My Coderwall
profile 


2013/10/11 Kamal Kaur 

> On Fri, Oct 11, 2013 at 6:43 PM, Leonardo Giordani
>  wrote:
> > Sorry, I forgot the User part of your question.
> >
> > Let me understand the exact relationship between codes, words and users:
> do
> > those words or codes come from a form? Or are saved in the DB for each
> user?
>
> Actually I have to search for client details (from UserProfile table)
> ignoring vowels. Because new users come from time to time. During
> their registration, the phonetic codes of all the words entered are
> saved (in CodeTable) along with the actual word.
>
> When a string is searched for, in search box, it is split into words
> and then these words are converted to phonetic codes which are to be
> searched in CodeTable. The words corresponding to matching codes will
> be searched for in UserProfile table which will be given as output for
> searched keywords i.e No matter if a user enters "Smyth" or "Smith",
> output will be on the basis of their sound. And thats all :)
>
> 
>
> > If you find the time to better describe the exact flow of your
> application I
> > hope I can help you find a good solution for your problem.
>
> Here you go :)
>
> --
> Kamaljeet Kaur
>
> --
> 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/CAP8Q%2Bxi-%2BPibMh_DsMyf14UUpZ_BkSEw5nWTRkdYyzoCDkpJWA%40mail.gmail.com
> .
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEhE%2BO%3DA%2B1MrXVBEYVS6fhvXGG4Yiem5t6wKdjzrfLnRG62QNw%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Django query from database

2013-10-11 Thread Kamal Kaur
On Fri, Oct 11, 2013 at 6:43 PM, Leonardo Giordani
 wrote:
> Sorry, I forgot the User part of your question.
>
> Let me understand the exact relationship between codes, words and users: do
> those words or codes come from a form? Or are saved in the DB for each user?

Actually I have to search for client details (from UserProfile table)
ignoring vowels. Because new users come from time to time. During
their registration, the phonetic codes of all the words entered are
saved (in CodeTable) along with the actual word.

When a string is searched for, in search box, it is split into words
and then these words are converted to phonetic codes which are to be
searched in CodeTable. The words corresponding to matching codes will
be searched for in UserProfile table which will be given as output for
searched keywords i.e No matter if a user enters "Smyth" or "Smith",
output will be on the basis of their sound. And thats all :)



> If you find the time to better describe the exact flow of your application I
> hope I can help you find a good solution for your problem.

Here you go :)

-- 
Kamaljeet Kaur

-- 
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/CAP8Q%2Bxi-%2BPibMh_DsMyf14UUpZ_BkSEw5nWTRkdYyzoCDkpJWA%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Django query from database

2013-10-11 Thread Leonardo Giordani
Sorry, I forgot the User part of your question.

Let me understand the exact relationship between codes, words and users: do
those words or codes come from a form? Or are saved in the DB for each user?

I ask this because I want to understand if you are trying to get a
relationship that already exists on the DB (so it is a problem of doing
good queries and building smart Python structures) or if you are trying to
manage some new data the user enters in your site.

If you find the time to better describe the exact flow of your application
I hope I can help you find a good solution for your problem.

Cheers

Leo

Leonardo Giordani
Author of The Digital Cat <http://lgiordani.github.com>
My profile on About.me <http://about.me/leonardo.giordani> - My GitHub
page<https://github.com/lgiordani>- My Coderwall
profile <https://coderwall.com/lgiordani>


2013/10/11 Kamal Kaur 

> On Fri, Oct 11, 2013 at 4:06 PM, Leonardo Giordani
>  wrote:
> > I think that you have to perform a query for each Code, extracting the
> list
> > of Word matching that Code and then merging all the lists.
>
> Exactly!
>
> > Since I don't know your models, I'll give you some general code, let me
> know
> > if you understand how to implement it exactly on your models.
>
> Here are these two models: http://tny.cz/82158e83
>
> 
> > This is the basic algorithm. You can then make all sorts of Python magic
> > tricks to shorten it or make it faster, but if you are not dealing with
> > billions of data I do suggest you to keep it simple and readable.
>
> Ok.
>
> > If you need to have each element in B appear just one time (uniqueness)
> just
> > perform a B = set(B) at the end.
>
> Ok.
>
> > Let me know if it works. =)
>
> Yes it will work! But after extending list B, I want to search the
> elements of list B from UserProfile table. Here the word can be
> anywhere and can be more than one times. Also two words in list B can
> be in same column. Here also the results must be unique.
>
> Also how to get the output in a template? The tuples containing
> elements of list B from UserProfile table are to be displayed in that
> template.
>
> Thanks ^_^
>
> --
> Kamaljeet Kaur
>
> --
> 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/CAP8Q%2BxidZD%2B6mo2z4POabcX_WBFPvEk%3D%3Dg%2BOPNET6u0SYmM%3DkQ%40mail.gmail.com
> .
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEhE%2BOm7A9kugRpE4S%2BmHLnRvYtO9w5RF9ZsWNwZzWxvxgBkVQ%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Django query from database

2013-10-11 Thread Kamal Kaur
On Fri, Oct 11, 2013 at 4:06 PM, Leonardo Giordani
 wrote:
> I think that you have to perform a query for each Code, extracting the list
> of Word matching that Code and then merging all the lists.

Exactly!

> Since I don't know your models, I'll give you some general code, let me know
> if you understand how to implement it exactly on your models.

Here are these two models: http://tny.cz/82158e83


> This is the basic algorithm. You can then make all sorts of Python magic
> tricks to shorten it or make it faster, but if you are not dealing with
> billions of data I do suggest you to keep it simple and readable.

Ok.

> If you need to have each element in B appear just one time (uniqueness) just
> perform a B = set(B) at the end.

Ok.

> Let me know if it works. =)

Yes it will work! But after extending list B, I want to search the
elements of list B from UserProfile table. Here the word can be
anywhere and can be more than one times. Also two words in list B can
be in same column. Here also the results must be unique.

Also how to get the output in a template? The tuples containing
elements of list B from UserProfile table are to be displayed in that
template.

Thanks ^_^

-- 
Kamaljeet Kaur

-- 
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/CAP8Q%2BxidZD%2B6mo2z4POabcX_WBFPvEk%3D%3Dg%2BOPNET6u0SYmM%3DkQ%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Django query from database

2013-10-11 Thread Leonardo Giordani
I think that you have to perform a query for each Code, extracting the list
of Word matching that Code and then merging all the lists.
Since I don't know your models, I'll give you some general code, let me
know if you understand how to implement it exactly on your models.

Assuming that the CodeTable is the representation of a Word model:

B = []
for code in A:
words = Word.objects.filter(code=code)
B.extend(words)

This is the basic algorithm. You can then make all sorts of Python magic
tricks to shorten it or make it faster, but if you are not dealing with
billions of data I do suggest you to keep it simple and readable.

If you need to have each element in B appear just one time (uniqueness)
just perform a B = set(B) at the end.

Let me know if it works. =)

Cheers
Leo



Leonardo Giordani
Author of The Digital Cat <http://lgiordani.github.com>
My profile on About.me <http://about.me/leonardo.giordani> - My GitHub
page<https://github.com/lgiordani>- My Coderwall
profile <https://coderwall.com/lgiordani>


2013/10/11 Kamal Kaur 

> Hello there,
>
> Hope you are doing well :)
>
> I have a problem regarding querying a list from two tables, the
> procedure goes like:
>
> Considering two tables from mysql database:
>
> 1. UserProfile table, with complete client details: First name, Last
> name, Address, email id, Contact number etc.
> 2. CodeTable, with only two columns 'Word' and 'Code'. Codes are
> soundex codes for the words in first column like:
>
> WordCode
> DavidD130
> Henry   H560
> OstroO236
> Milton   M435
> HenrooH560
>
> These 'words' are also contained in UserProfile table somewhere, can
> be in any column. I have a list A with soundex codes, entered by user,
> obtained with request.GET like:
> A= ['D130', 'H560', 'O236']
>
> Here starts the problem, I have to fetch 'Words' from CodeTable
> corresponding to the 'Codes' in list A, meaning that I need another
> list B, like:
>
> B = ['David', 'Henry', 'Ostro', ' Henroo']
>
> Because the code H560 is same for ' Henroo', it will also be there in
> list B as we are searching for all the words that have 'codes' in list
> A.
>
> For this list B, I want to search all the client details i.e. I want
> to display all the clients that have any of the words in list B from
> UserProfile table.
>
> I am not getting how to accomplish this searching using Django
> queries. I am not able to make a view/function for this logic. Please
> help and feel free to ask details if problm is not clear.
>
> Thanks ^_^
>
>
> --
> Kamaljeet Kaur
>
> --
> 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/CAP8Q%2BxhO%3DeZJjdui4OOw1T3V2QqtJW_PnC-BTTCDdBogipc8sw%40mail.gmail.com
> .
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEhE%2BO%3DFRyds-AOGAOd47mRgtjEz5u4TAKVx6S%2BPNQ5Qfb3WDg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Django query from database

2013-10-11 Thread Kamal Kaur
Hello there,

Hope you are doing well :)

I have a problem regarding querying a list from two tables, the
procedure goes like:

Considering two tables from mysql database:

1. UserProfile table, with complete client details: First name, Last
name, Address, email id, Contact number etc.
2. CodeTable, with only two columns 'Word' and 'Code'. Codes are
soundex codes for the words in first column like:

WordCode
DavidD130
Henry   H560
OstroO236
Milton   M435
HenrooH560

These 'words' are also contained in UserProfile table somewhere, can
be in any column. I have a list A with soundex codes, entered by user,
obtained with request.GET like:
A= ['D130', 'H560', 'O236']

Here starts the problem, I have to fetch 'Words' from CodeTable
corresponding to the 'Codes' in list A, meaning that I need another
list B, like:

B = ['David', 'Henry', 'Ostro', ' Henroo']

Because the code H560 is same for ' Henroo', it will also be there in
list B as we are searching for all the words that have 'codes' in list
A.

For this list B, I want to search all the client details i.e. I want
to display all the clients that have any of the words in list B from
UserProfile table.

I am not getting how to accomplish this searching using Django
queries. I am not able to make a view/function for this logic. Please
help and feel free to ask details if problm is not clear.

Thanks ^_^


-- 
Kamaljeet Kaur

-- 
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/CAP8Q%2BxhO%3DeZJjdui4OOw1T3V2QqtJW_PnC-BTTCDdBogipc8sw%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Denis Chernoshchekov
Your right... I can't testing now.


2013/10/9 Hélio Miranda 

> gives error:
> 'BaseList' object has no attribute 'values'
>
> The query has to be the same as I stated it works:
> *
> Player.objects.filter(country__in=Country.objects.filter(nationality__in=Nationality.objects.filter(name='Espanhola')))
> *
>
> --
> 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/7a4cf4fe-0c5a-40ff-92fc-60c51164239f%40googlegroups.com
> .
>
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2BX6QOWHTn7xc%3DY11b8%2BU5sTP%3DCu03AhSvGM5F3R66wxO8AWUQ%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Hélio Miranda
gives error:
'BaseList' object has no attribute 'values'

The query has to be the same as I stated it works:
*
Player.objects.filter(country__in=Country.objects.filter(nationality__in=Nationality.objects.filter(name='Espanhola')))
*

-- 
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/7a4cf4fe-0c5a-40ff-92fc-60c51164239f%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Denis Chernoshchekov
try this solution
http://plnkr.co/edit/cyM6AmZcyFVUU6soFKhB


2013/10/9 Denis Chernoshchekov 

> ok, i understand, i minute.
>
>
> 2013/10/9 Denis Chernoshchekov 
>
>> *fld_name = 'nationality_in' *must be with double '_'* **fld_name =
>> 'nationality__in'*
>>
>>
>> 2013/10/9 Denis Chernoshchekov 
>>
>>> Sorry, i don't understand you... You can control all your values for all
>>> fields, you can generate dict which you like.
>>>
>>>
>>> 2013/10/9 Hélio Miranda 
>>>
 I put that work, I wanted to know was how to put in the code, because
 you can not do the same to position

 --
 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/7ab55030-ef63-42de-b4b4-cad45b7c287c%40googlegroups.com
 .

 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2BX6QOULQK0n5mgAsyDGwFbYrJqtVYxZtSUZ4wm_fjK6r_7tHg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Denis Chernoshchekov
ok, i understand, i minute.


2013/10/9 Denis Chernoshchekov 

> *fld_name = 'nationality_in' *must be with double '_'* **fld_name =
> 'nationality__in'*
>
>
> 2013/10/9 Denis Chernoshchekov 
>
>> Sorry, i don't understand you... You can control all your values for all
>> fields, you can generate dict which you like.
>>
>>
>> 2013/10/9 Hélio Miranda 
>>
>>> I put that work, I wanted to know was how to put in the code, because
>>> you can not do the same to position
>>>
>>> --
>>> 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/7ab55030-ef63-42de-b4b4-cad45b7c287c%40googlegroups.com
>>> .
>>>
>>> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2BX6QOUf7Ck0Y9ptjn_FaJLEaPzPdmas01CRPW_QPNVg39%2BD8A%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Denis Chernoshchekov
*fld_name = 'nationality_in' *must be with double '_'* **fld_name =
'nationality__in'*


2013/10/9 Denis Chernoshchekov 

> Sorry, i don't understand you... You can control all your values for all
> fields, you can generate dict which you like.
>
>
> 2013/10/9 Hélio Miranda 
>
>> I put that work, I wanted to know was how to put in the code, because you
>> can not do the same to position
>>
>> --
>> 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/7ab55030-ef63-42de-b4b4-cad45b7c287c%40googlegroups.com
>> .
>>
>> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2BX6QOW%3D_kZw7BWo6TWL3fzk92U89i7rqkw8yZ3jg-mxRuwKsQ%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Denis Chernoshchekov
Sorry, i don't understand you... You can control all your values for all
fields, you can generate dict which you like.


2013/10/9 Hélio Miranda 

> I put that work, I wanted to know was how to put in the code, because you
> can not do the same to position
>
> --
> 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/7ab55030-ef63-42de-b4b4-cad45b7c287c%40googlegroups.com
> .
>
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2BX6QOVmFDZ5kexgJgiec9GeLazOcA7fgAVdp-Ybv%3DfUmgchig%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Hélio Miranda
was trying something like this:
*if fld_name == 'nationality':*
*fld_name = 'nationality_in'*
*value = 
Player.objects.filter(country__in=Country.objects.filter(nationality__in=Nationality.objects.filter(name=value)))
*

But it does not work

-- 
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/360f22d0-de14-4ec8-b9d4-3c4079f6ee39%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Hélio Miranda
I put that work, I wanted to know was how to put in the code, because you 
can not do the same to position

-- 
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/7ab55030-ef63-42de-b4b4-cad45b7c287c%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Denis Chernoshchekov
Try this - *Player.objects.filter(country__in=**
Nationality.objects.filter(name='Espanhola').distinct('country').values('country'))
*


2013/10/9 Hélio Miranda 

> yes, that was it ...
> Just one more thing, if I would like to create the nationality of the
> player, so that the filter is:
> *
> Player.objects.filter(country__in=Country.objects.filter(nationality__in=Nationality.objects.filter(name='Espanhola')))
> *
> *
> *
> where only the step nationality, as I do, not only gives an if?
>
> --
> 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/c8a6-6f7f-4603-9834-c94e426208e0%40googlegroups.com
> .
>
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2BX6QOVx4ad26UpgA6YEPvQy%3DjNiNfQADgaAPW%2B%2BBNe4xBtexQ%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Hélio Miranda
yes, that was it ...
Just one more thing, if I would like to create the nationality of the 
player, so that the filter is:
*
Player.objects.filter(country__in=Country.objects.filter(nationality__in=Nationality.objects.filter(name='Espanhola')))
*
*
*
where only the step nationality, as I do, not only gives an if?

-- 
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/c8a6-6f7f-4603-9834-c94e426208e0%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Denis Chernoshchekov
See, maybe like this?
http://plnkr.co/edit/cyM6AmZcyFVUU6soFKhB


2013/10/9 Hélio Miranda 

> I have code like this:
> http://plnkr.co/edit/L1ByIyFyaEdgwrfVU7Jr
>
> Just do not know how to put this part in the code ...
> Where do I put this part?
>
> --
> 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/5b896e03-fa40-4dbd-8075-8cad2ac954a8%40googlegroups.com
> .
>
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2BX6QOXpZaaWf89JobtYMvZCD9JvJdyVtrDNaR2VtWZZK4A5Dg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Hélio Miranda
I have code like this:
http://plnkr.co/edit/L1ByIyFyaEdgwrfVU7Jr

Just do not know how to put this part in the code ...
Where do I put this part?

-- 
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/5b896e03-fa40-4dbd-8075-8cad2ac954a8%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Denis Chernoshchekov
For position you may have dict like - **{' position__in ':
Position.objects. filter(name=positionpost) }
9 жовт. 2013 11:45, користувач "Hélio Miranda"  написав:

> hi, thanks that helped a lot.
> But I have a problem which is, for example when I do a filter by position,
> is not direct as other fields like name or surname. For the position I have
> to type this:
> *
> Player.objects.filter(position__in=Position.objects.filter(name=positionpost))
> *
> How can I implement this in code?
> Can you 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.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/f2e7c115-275d-4fab-9dab-f5c0a10c9544%40googlegroups.com
> .
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2BX6QOVRDjrjU3CrDZxsREHYMt5MzuJ5k3_14WPMSycO-fnKMg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Hélio Miranda
hi, thanks that helped a lot.
But I have a problem which is, for example when I do a filter by position, 
is not direct as other fields like name or surname. For the position I have 
to type this:
*
Player.objects.filter(position__in=Position.objects.filter(name=positionpost))
*
How can I implement this in code?
Can you 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/f2e7c115-275d-4fab-9dab-f5c0a10c9544%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Denis Chernoshchekov
You can pass filter params like a dict -
Player.objects.filter(**your_dict), so you need only prepare your dict from
POST.
8 жовт. 2013 17:42, користувач "Hélio Miranda"  написав:

> Hi
> Here I am having a problem which is as follows:
> I 'm getting parameters via post to make querys depending on paramtros I
> are passed ... doing gender filters.
> So I'm doing well
> *def filter(request):*
> *if request.method == 'POST':*
> *namepost = request.POST.get('name')*
> *surnamepost = request.POST.get('surname')*
> *
> *
> *if namepost != None and surnamepost != None:*
> *result = [a.get_json() for a in
> Player.objects.filter((Q(name=namepost) & Q(surname=surnamepost)))]*
> *   elif namepost != None and surnamepost == None:*
> *result = [a.get_json() for a in
> Player.objects.filter(name=namepost)]*
> **
> *data = {"meta": {"total_count":len(result)}, "objects": result}*
> *aa = json.dumps(data)*
> *return HttpResponse(aa, content_type='application/json')*
>
> Is working properly , the problem is :
> If it were only these two parameters , there was no problem , was to
> complete the rest of the hypotheses ... the problem is that I can have up
> to 10 parameters passed by post to the filters , and I never know which are
> passed , can be 1 , 2, 4, ... as the user makes the filter ...
>
> But doing so would take a lot of ifs , it would have many chances ...
> is there any way I can do this another way ?
> Someone can 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.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/fc851085-d5bb-4567-b830-d25cdd66e499%40googlegroups.com
> .
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2BX6QOXTgDCfXiB_CsqgRjg_V5ngho5gk%3DoZEfP8WhpwfcB2Kg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-09 Thread Hélio Miranda
I was testing you sent me, but it is giving me error ... is giving this 
error: *expected string or buffer*

-- 
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/08b4c60e-585e-483c-b520-739a1efa615a%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query parameters for receiving post

2013-10-08 Thread Ramiro Morales
On Tue, Oct 8, 2013 at 11:42 AM, Hélio Miranda  wrote:
>
> Hi
> Here I am having a problem which is as follows:
> I 'm getting parameters via post to make querys depending on paramtros I are 
> passed ... doing gender filters.
> So I'm doing well
> def filter(request):
> if request.method == 'POST':
> namepost = request.POST.get('name')
> surnamepost = request.POST.get('surname')
>
> if namepost != None and surnamepost != None:
> result = [a.get_json() for a in 
> Player.objects.filter((Q(name=namepost) & Q(surname=surnamepost)))]
>elif namepost != None and surnamepost == None:
> result = [a.get_json() for a in 
> Player.objects.filter(name=namepost)]
>
> data = {"meta": {"total_count":len(result)}, "objects": result}
> aa = json.dumps(data)
> return HttpResponse(aa, content_type='application/json')
>
> Is working properly , the problem is :
> If it were only these two parameters , there was no problem , was to complete 
> the rest of the hypotheses ... the problem is that I can have up to 10 
> parameters passed by post to the filters , and I never know which are passed 
> , can be 1 , 2, 4, ... as the user makes the filter ...
>
> But doing so would take a lot of ifs , it would have many chances ...
> is there any way I can do this another way ?
> Someone can help me ?

I can't thes this now but hopefully something similar to thois could
be of help: https://dpaste.de/FTnt

-- 
Ramiro Morales
@ramiromorales

-- 
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/CAO7PdF80K5SxRAKXVgi55JtjuRRcwNq58Df-DZXZrZeuJSBRdg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: How to Query account/profile information for multiple account and allowing user edit or update acount

2013-10-08 Thread Okorie Emmanuel
Thanks for your response

This is what i want to do,
I want to create an app that have two different users
that is teachers(one type of user) and student(another type of user)
the problem is how to create them without using 

AUTH_USER_MODEL = 'myapp.MyUser'
since it is  for one kind of user only.

I have created the model as shown in last post
but how to query individual details in their 
respective profile is the problem.

Any way out. thanks 

-- 
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/4e7d04d2-fe57-45cd-8287-ae4aa55e1ba4%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Query parameters for receiving post

2013-10-08 Thread Hélio Miranda
Hi
Here I am having a problem which is as follows:
I 'm getting parameters via post to make querys depending on paramtros I 
are passed ... doing gender filters.
So I'm doing well
*def filter(request):*
*if request.method == 'POST':*
*namepost = request.POST.get('name')*
*surnamepost = request.POST.get('surname')*
*
*
*if namepost != None and surnamepost != None:*
*result = [a.get_json() for a in 
Player.objects.filter((Q(name=namepost) & Q(surname=surnamepost)))]*
*   elif namepost != None and surnamepost == None:*
*result = [a.get_json() for a in 
Player.objects.filter(name=namepost)]*
**
*data = {"meta": {"total_count":len(result)}, "objects": result}*
*aa = json.dumps(data)*
*return HttpResponse(aa, content_type='application/json')*

Is working properly , the problem is :
If it were only these two parameters , there was no problem , was to 
complete the rest of the hypotheses ... the problem is that I can have up 
to 10 parameters passed by post to the filters , and I never know which are 
passed , can be 1 , 2, 4, ... as the user makes the filter ...

But doing so would take a lot of ifs , it would have many chances ...
is there any way I can do this another way ?
Someone can 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/fc851085-d5bb-4567-b830-d25cdd66e499%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query field with reference

2013-10-08 Thread Hélio Miranda
I managed to solve the problem, I did so:
*result = [a.get_json() for a in 
Player.objects.filter(position__in=Position.objects.filter(name=positionpost))]
*

Thanks for the trouble

-- 
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/bcaf95d0-549b-4249-af86-ae1392cfe437%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query field with reference

2013-10-08 Thread Hélio Miranda
Gives error says:
DD is not a valid ObjectId

For the DD not objectId of reference

-- 
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/80e66eeb-5f84-4e82-8f97-6463fb1227b6%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Query field with reference

2013-10-08 Thread Leonardo Giordani
I do not know MongoDB, so sorry if I get it wrong. I'd say that you have to
write

*result = [a.get_json() for a in
Player.objects.filter(position__position_name='DD')]
*
since in your attached document you set it this way (line 53).
Try and let me know

Leo


Leonardo Giordani
Author of The Digital Cat <http://lgiordani.github.com>
My profile on About.me <http://about.me/leonardo.giordani> - My GitHub
page<https://github.com/lgiordani>- My Coderwall
profile <https://coderwall.com/lgiordani>


2013/10/8 Hélio Miranda 

> Hi
> I was trying to make a query in a field that has refencia to another
> collection, like this:
> *result = [a.get_json() for a in
> Player.objects.filter(position__name='DD')]*
>
> But it is returning me empty, and I have a player with the position DD
> I'm using mongodb as a database.
>
> In my Document is thus:
> http://plnkr.co/edit/FHH2hZh26OiLMKTk2ToO?p=info
>
> Does anyone know what I'm doing wrong?
>
> thank you
>
> --
> 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/47c58f74-484b-4668-9678-7a50fdea842f%40googlegroups.com
> .
> 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEhE%2BOmUqH2kfcY-Ve0%3D9-HHAtP9sd%2BpyT-358PO9M5Cyq4J%3Dg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Query field with reference

2013-10-08 Thread Hélio Miranda
Hi
I was trying to make a query in a field that has refencia to another 
collection, like this:
*result = [a.get_json() for a in Player.objects.filter(position__name='DD')]
*

But it is returning me empty, and I have a player with the position DD
I'm using mongodb as a database.

In my Document is thus:
http://plnkr.co/edit/FHH2hZh26OiLMKTk2ToO?p=info

Does anyone know what I'm doing wrong?

thank you

-- 
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/47c58f74-484b-4668-9678-7a50fdea842f%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: How to Query account/profile information for multiple account and allowing user edit or update acount

2013-09-30 Thread Daniel Roseman
On Monday, 30 September 2013 19:33:31 UTC+1, Okorie Emmanuel wrote:

> I have two problems 
>
> 1. How can i populate the account 
>information of each user, this 
>what i have done but only info on
>user models populates, the info on extended 
>field does not show on my template
>
> # models.py
>class Student(Models.model):
>   user = foreignkey(user)
>   sex= models.charfied()
>  ..
>
>  class Teacher(Models.model):
>   user = foreignkey(user)
>   sex= models.charfied()
>   salary models.charfield()
>  ..
>
>
>
># views.py
>
>  @login_required(login_url='/
> login/')
> def account(request, template_name="account.html"):
> if not request.user.is_authenticated():
> return HttpResponseRedirect('/login/')
> regis = property(lambda u: Candidate.objects.get(User=u)[0])
> context = {'regis': regis}
> return render_to_response('account.html', context, 
> context_instance=RequestContext(request))
>  
>

What is that property/lambda stuff supposed to be doing? You *seem* to be 
trying to define something that will get a Candidate from a user, but I 
don't understand why you're wrapping it in 'property', and then of course 
you don't ever call it or pass it a User. If you did call it, you'd no 
doubt get multiple errors, for example `get` only returns a single object 
so indexing it with [0] is bound to raise an exception.

Also, you might want to explain the relationship between a Candidate and 
the Student/Teacher models you've shown above. 
--
DR.

-- 
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/beedfe13-35a8-4def-a0e4-72dc478775fb%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: How to Query account/profile information for multiple account and allowing user edit or update acount

2013-09-30 Thread Frank Bieniek

Please try, django-userena, or django-registration,
both deal with userdetails.

Thx
Frank


Am 30.09.13 20:33, schrieb Okorie Emmanuel:

I have two problems

1. How can i populate the account
   information of each user, this
   what i have done but only info on
   user models populates, the info on extended
   field does not show on my template

# models.py
   class Student(Models.model):
  user = foreignkey(user)
  sex= models.charfied()
 ..

 class Teacher(Models.model):
  user = foreignkey(user)
  sex= models.charfied()
  salary models.charfield()
 ..



   # views.py

 @login_required(login_url='/
login/')
def account(request, template_name="account.html"):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
regis = property(lambda u: Candidate.objects.get(User=u)[0])
context = {'regis': regis}
return render_to_response('account.html', context, 
context_instance=RequestContext(request))


#account.html

{% extends "base.html" %}

{% block wrapper %}
 welcome  {{ user.username }}
Email: {{ user.email }}
Name: {{ regis.u.first_name }}
Sex: {{ regis.sex }}
surname: {{ regis.last_name }}
Date of birth: {{ regis.dob }}
Marital status: {{ regis.marital_status }}
passport: {{ regis.passport }}


{% endblock %}

{{user.username}}, {{ user.email }} shows but
the rest does not show

2. i Have the profile form to enable user
edit their account anytime they want,
but i can't figure the code around it

any solution to this problem
thanks
--
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/50bfe62a-556b-4b29-8ba9-50d58006c2c1%40googlegroups.com.

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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5249C868.4020203%40produktlaunch.de.
For more options, visit https://groups.google.com/groups/opt_out.


How to Query account/profile information for multiple account and allowing user edit or update acount

2013-09-30 Thread Okorie Emmanuel
I have two problems 

1. How can i populate the account 
   information of each user, this 
   what i have done but only info on
   user models populates, the info on extended 
   field does not show on my template

# models.py
   class Student(Models.model):
  user = foreignkey(user)
  sex= models.charfied()
 ..

 class Teacher(Models.model):
  user = foreignkey(user)
  sex= models.charfied()
  salary models.charfield()
 ..


   
   # views.py
   
 @login_required(login_url='/
login/')
def account(request, template_name="account.html"):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
regis = property(lambda u: Candidate.objects.get(User=u)[0])
context = {'regis': regis}
return render_to_response('account.html', context, 
context_instance=RequestContext(request))

#account.html

{% extends "base.html" %}

{% block wrapper %}
 welcome  {{ user.username }}
Email: {{ user.email }}
Name: {{ regis.u.first_name }}
Sex: {{ regis.sex }}
surname: {{ regis.last_name }}
Date of birth: {{ regis.dob }}
Marital status: {{ regis.marital_status }}
passport: {{ regis.passport }}


{% endblock %}

{{user.username}}, {{ user.email }} shows but
the rest does not show 

2. i Have the profile form to enable user
edit their account anytime they want,
but i can't figure the code around it

any solution to this problem
thanks


-- 
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/50bfe62a-556b-4b29-8ba9-50d58006c2c1%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Basic query regarding admin CSS

2013-09-28 Thread Jason S
Hi, 
This is fixed, I think it was as I was missing one of the entries below:
 37 MIDDLEWARE_CLASSES = (
 38 # This loads the index definitions, so it has to come first
 39 'autoload.middleware.AutoloadMiddleware',
 40
 41 'django.middleware.common.CommonMiddleware',
 42 'django.contrib.sessions.middleware.SessionMiddleware',
 43 'django.contrib.messages.middleware.MessageMiddleware',
 44 'django.contrib.auth.middleware.AuthenticationMiddleware',
 45 )
 46
 47 TEMPLATE_CONTEXT_PROCESSORS = (
 48 'django.contrib.auth.context_processors.auth',
 49 'django.core.context_processors.request',
 50 'django.core.context_processors.media',
 51 'django.core.context_processors.static'
 52 )

On Friday, 27 September 2013 19:54:21 UTC-10, Jason S wrote:
>
> Hi,
> I'm new to development and have just gone from some python and django 
> tuts, on my way to developing my first app.
> I've created a model and can view it under the /admin page, however the 
> page does not use any of the pretty CSS you see in the tutorials because it 
> can't find the files:
>
> INFO:root:"GET /admin/ HTTP/1.1" 200 -
> INFO:root:"GET /admin/admin/css/base.css HTTP/1.1" 404 -
> INFO:root:"GET /admin/admin/css/dashboard.css HTTP/1.1" 404 -
>
> I've got the css, img and js folders for the admin site in the following 
> places:
> [myproject]/admin/admin
> [myproject]/templates/admin/admin
>
> I tried to view one of the CSS files directly via the browser for more 
> information and it displays the urls it searches.
> I'd appreciate if someone could tell me what i'm missing.
>
> http://192.168.20.204:8080/admin/admin/css/dashboard.css
> Page not found (404)Request Method:GETRequest URL:
> http://192.168.20.204:8080/admin/admin/css/dashboard.css
>
> Using the URLconf defined in urls, Django tried these URL patterns, in 
> this order:
>
>1. ^_ah/warmup$
>2. ^media/(?P.*)$
>3. ^admin/ ^$ [name='index']
>4. ^admin/ ^logout/$ [name='logout']
>5. ^admin/ ^password_change/$ [name='password_change']
>6. ^admin/ ^password_change/done/$ [name='password_change_done']
>7. ^admin/ ^jsi18n/$ [name='jsi18n']
>8. ^admin/ ^r/(?P\d+)/(?P.+)/$
>9. ^admin/ ^(?P\w+)/$ [name='app_list']
>10. ^admin/ ^blogtut/post/
>11. ^admin/ ^blogtut/comment/
>12. ^admin/ ^auth/user/
>13. ^admin/ ^blogtut/measurementtype/
>14. ^admin/ ^blogtut/measurementunits/
>15. ^$
>16. ^login/$
>17. ^logout/$
>18. ^posts/new/$
>19. ^posts/$
>20. ^$ [name='home']
>21. ^post/(?P[a-zA-Z0-9-]+)/$ [name='post']
>
>

-- 
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.


Basic query regarding admin CSS

2013-09-28 Thread Jason S
Hi,
I'm new to development and have just gone from some python and django tuts, 
on my way to developing my first app.
I've created a model and can view it under the /admin page, however the 
page does not use any of the pretty CSS you see in the tutorials because it 
can't find the files:

INFO:root:"GET /admin/ HTTP/1.1" 200 -
INFO:root:"GET /admin/admin/css/base.css HTTP/1.1" 404 -
INFO:root:"GET /admin/admin/css/dashboard.css HTTP/1.1" 404 -

I've got the css, img and js folders for the admin site in the following 
places:
[myproject]/admin/admin
[myproject]/templates/admin/admin

I tried to view one of the CSS files directly via the browser for more 
information and it displays the urls it searches.
I'd appreciate if someone could tell me what i'm missing.

http://192.168.20.204:8080/admin/admin/css/dashboard.css
Page not found (404)Request Method:GETRequest URL:
http://192.168.20.204:8080/admin/admin/css/dashboard.css

Using the URLconf defined in urls, Django tried these URL patterns, in this 
order:

   1. ^_ah/warmup$
   2. ^media/(?P.*)$
   3. ^admin/ ^$ [name='index']
   4. ^admin/ ^logout/$ [name='logout']
   5. ^admin/ ^password_change/$ [name='password_change']
   6. ^admin/ ^password_change/done/$ [name='password_change_done']
   7. ^admin/ ^jsi18n/$ [name='jsi18n']
   8. ^admin/ ^r/(?P\d+)/(?P.+)/$
   9. ^admin/ ^(?P\w+)/$ [name='app_list']
   10. ^admin/ ^blogtut/post/
   11. ^admin/ ^blogtut/comment/
   12. ^admin/ ^auth/user/
   13. ^admin/ ^blogtut/measurementtype/
   14. ^admin/ ^blogtut/measurementunits/
   15. ^$
   16. ^login/$
   17. ^logout/$
   18. ^posts/new/$
   19. ^posts/$
   20. ^$ [name='home']
   21. ^post/(?P[a-zA-Z0-9-]+)/$ [name='post']

-- 
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.


Django query Advanced

2013-09-26 Thread Hélio Miranda
I am trying a query like this:

result = json.dumps([a.get_json() for a in 
Player.objects.filter((Q(name=namepost) | Q(surname="Coimbra")))])
   return HttpResponse (result, content_type = 'application / json')

But it gives me the following error: Not a query object: (AND: ('surname', 
'Coimbra'), ('name', u'Rui ')). Did you intend to use key = value?

get_json def (self):
  return {
'name': self.name,
'surname': self.surname,
'country': [{'name': b.name} for b in self.country]
   }

If I do well

result = json.dumps([a.get_json() for a in 
Player.objects.filter(name=namepost)])

works well

What am I doing wrong? Someone can 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.


Django ORM generating the wrong query for recent friends of an user

2013-09-24 Thread Arthur Silva
Here're my models


class PingUser(AbstractUser):
friends = models.ManyToManyField("self", through="Friendship", 
symmetrical=False)

class Friendship(TimestampedModel, SerializeMixin):
STATUS_CHOICES = (
("pending", "Pending"),
("friend", "Friend"),
("favorite", "Favorite")
)
user = models.ForeignKey(PingUser, related_name="friendships")
friend = models.ForeignKey(PingUser, 
related_name="friendships_reverse")
status = models.CharField(max_length=20, 
default=STATUS_CHOICES[0][0], choices=STATUS_CHOICES)

class Meta:
unique_together = [('user', 'friend')]



The code I'm using to get the most recent friends of user 4


id = 4
friendships = Friendship.objects.exclude(status="pending").filter(
~Q(user__friendships__status="pending"), 
user__friendships__friend_id=id).order_by("-created_at")


I also tried several combinations like grouping all filtering inside one 
filter() but the query is the same


Generated query


SELECT `sample_app_friendship`.`id`,
   `sample_app_friendship`.`created_at`,
   `sample_app_friendship`.`updated_at`,
   `sample_app_friendship`.`user_id`,
   `sample_app_friendship`.`friend_id`,
   `sample_app_friendship`.`status`
FROM `sample_app_friendship`
INNER JOIN `sample_app_pinguser` ON (`sample_app_friendship`.`user_id` 
= `sample_app_pinguser`.`id`)
INNER JOIN `sample_app_friendship` T5 ON (`sample_app_pinguser`.`id` = 
T5.`user_id`)
WHERE (NOT (`sample_app_friendship`.`status` = 'pending')
   AND NOT ((`sample_app_friendship`.`user_id` IN
   (SELECT U2.`user_id`
FROM `sample_app_friendship` U2
WHERE (U2.`status` = 'pending'
   AND U2.`user_id` IS NOT NULL))
 AND `sample_app_pinguser`.`id` IS NOT NULL))
   AND T5.`friend_id` = 4)



The desired query is actually


SELECT `sample_app_friendship`.`id`,
   `sample_app_friendship`.`created_at`,
   `sample_app_friendship`.`updated_at`,
   `sample_app_friendship`.`user_id`,
   `sample_app_friendship`.`friend_id`,
   `sample_app_friendship`.`status`
FROM `sample_app_friendship`
INNER JOIN `sample_app_pinguser` ON (`sample_app_friendship`.`user_id` 
= `sample_app_pinguser`.`id`)
INNER JOIN `sample_app_friendship` T5 ON (`sample_app_pinguser`.`id` = 
T5.`user_id`)
WHERE (NOT (`sample_app_friendship`.`status` = 'pending')
   AND (NOT T5.`status` = 'pending')
   AND T5.`friend_id` = 4)

Someone more experienced can shed some light?

Thanks!

-- 
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: Complex query

2013-09-09 Thread Drew Ferguson
On Mon, 9 Sep 2013 06:57:46 -0700 (PDT)
Yegor Roganov  wrote:

> Thanks for you replies.
> But I wonder how real production web sites deal with this problem. The 
> problem is that I want to display about 30 topics per page which would 
> result in 30+1 queries if implemented naively. If I write the required 
> query in raw SQL, it should be faster, but probably not very fast
> anyway. Also I don't know how to cache properly since topics should be
> ordered by most recent posts (that is, if someone posts to topic on
> third page, this topic should become the first one on the first page).
> 

If you were using Postgres or similar, you could create some triggers
and/or stored-procedures that maintained an active list of 30 target
items - perhaps with a flag in one of the database tables. Then create a
view to generate the list of 30 items you needed.

This way the ORM & Django SQL access is reduced to a single query on the
view. The heavy lifting is all done server-side as comments/articles are
saved

Could this work?
-- 
Drew Ferguson

-- 
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.


<    5   6   7   8   9   10   11   12   13   14   >