Re: Can the new `Prefetch` solve my problem?

2015-03-02 Thread Simon Charette
Hi cool-RR,

The following should do:

filtered_chairs = Chair.objects.filter(some_other_lookup=whatever)
desks = Desk.objects.prefetch_related(
PrefetchRelated('chairs', filtered_chairs, to_attr='filered_chairs'),
PrefetchRelated('nearby_chairs', filtered_chairs, 
to_attr='filtered_nearby_chairs'),
)

from itertools import chain
for desk in desks:
for chair in chain(desk.filtered_chairs, desk.filtered_nearby_chairs):
# 

It will issue only three queries independently of the number of Chair or 
Desks you have.

Simon

Le mercredi 25 février 2015 15:05:50 UTC-5, cool-RR a écrit :
>
> Hi guys,
>
> I'm trying to solve a problem using the new `Prefetch` but I can't figure 
> out how to use it. 
>
> I have these models:
>
> class Desk(django.db.models.Model):
> pass
> 
> class Chair(django.db.models.Model):
> desk = django.db.models.Foreignkey('Desk', related_name='chair',)
> nearby_desks = django.db.models.ManyToManyField(
> 'Desk',
> blank=True,
> )
>
> I want to get a queryset for `Desk`, but it should also include a 
> prefetched attribute `favorite_or_nearby_chairs`, whose value should be 
> equal to: 
>
> Chair.objects.filter(
> (django.db.models.Q(nearby_desks=desk) | 
> django.db.models.Q(desk=desk)),
> some_other_lookup=whatever,
> )
>
> Is this possible with `Prefetch`? I couldn't figure out how to use the 
> arguments.
>
>
> Thanks,
> Ram.
>

-- 
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/726492e7-5f82-4690-a97c-20743592c3f8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Query optimization - From 3 queries to 2

2015-03-02 Thread Simon Charette
Hi Humberto,

The following should do:

Provider.objects.prefetch_related(
Prefetch('service_types', 
ServiceType.objects.select_related('service_type_category'))
)

P.S. Next time you post a question try to remove data unrelated to your 
issue from your example (e.g `countries` and `user` reference).

Simon

Le dimanche 1 mars 2015 18:33:17 UTC-5, Humberto Moreira a écrit :
>
> I basically have to display a list of service providers and in each, I 
> need to display the categories of service they offer.
>
> So as an example:
>
> Possible Service Type Categories:
>
> [id: 1, name:'Programming'][id: 2, name:'Design']
>
> Possible Service Types:
>
> [id: 1, name: 'PHP Service', service_type_category_id: 1][id: 2, name: 'JAVA 
> Service', service_type_category_id: 1][id: 3, name: 'Web Design Service', 
> service_type_category_id: 2]
>
> Example of Display Results:
>
> Company Blue offers 'Programming'Company Test offers 'Programming' and 
> 'Design'Company Orange offers 'Design' 
>
> I'm trying to write the least number of queries:
>
> I have these models:
>
> class ServiceTypeCategory( BaseModel ):
>
> # Model Attributes
> name = models.CharField( _( "name" ), max_length = 40 )
>
> class ServiceType( BaseModel ):
>
> # Model Attributes
> service_type_category = models.ForeignKey( 'ServiceTypeCategory', 
> verbose_name = _( 'category' ) )
> name = models.CharField( _( "name" ), max_length = 60 )
> description = models.TextField( _( "description" ) )
>
> class Provider( BaseModel ):
>
> # Model Attributes
> display_name = models.CharField( _( "name" ), max_length = 80 )
>
> # Many to many relations
> countries = models.ManyToManyField( 'core.Country' ) # countries this 
> provider support
> service_types = models.ManyToManyField( 'ServiceType', through = 
> 'Provider_ServiceTypes', related_name = 'service_types' )
>
> class Provider_ServiceTypes( BaseModel ):
>
> # Model Attributes
> service_type = models.ForeignKey( 'ServiceType', verbose_name = _( 
> 'service type' ) )
> provider = models.ForeignKey( 'Provider', verbose_name = _( 'provider' ) )
> is_top = models.BooleanField( _( "is top service" ), default = False )
>
> Then, to run the query, I have the following:
>
> providers = Provider.objects.select_related(
> 'user',).prefetch_related(
> Prefetch(
> 'service_types__service_type_category',
> queryset = ServiceTypeCategory.objects
> .only( 'name' )
> )).filter(
> countries = country_id,).only(
> 'id', 'display_name', 'user').order_by(
> '-user__last_login')
>
> This works out well, but it runs the 3 following queries:
>
> SELECT app_provider.id, app_provider.user_id, app_provider.display_name, 
> core_user.id, core_user.password, core_user.last_login, 
> core_user.is_superuser, core_user.created_date, core_user.modified_date, 
> core_user.email, core_user.name, core_user.is_active, core_user.is_admin 
> FROM app_provider 
> INNER JOIN app_provider_countries ON ( app_provider.id = 
> app_provider_countries.provider_id ) 
> INNER JOIN core_user ON ( app_provider.user_id = core_user.id ) 
> LEFT OUTER JOIN core_userpersonal ON ( core_user.id = 
> core_userpersonal.user_id ) 
> LEFT OUTER JOIN core_userstats ON ( core_user.id = core_userstats.user_id ) 
> WHERE app_provider_countries.country_id = 204 
> ORDER BY core_userstats.total_reviews DESC, core_userstats.total_contracts 
> DESC, core_userstats.total_answers DESC, core_user.last_login DESC LIMIT 5
>
>
> SELECT (app_provider_servicetypes.provider_id) AS 
> _prefetch_related_val_provider_id, app_servicetype.id, 
> app_servicetype.created_date, app_servicetype.modified_date, 
> app_servicetype.service_type_category_id, app_servicetype.name, 
> app_servicetype.description 
> FROM app_servicetype 
> INNER JOIN app_provider_servicetypes ON ( app_servicetype.id = 
> app_provider_servicetypes.service_type_id ) 
> WHERE app_provider_servicetypes.provider_id IN (2)
>
>
> SELECT app_servicetypecategory.id, app_servicetypecategory.name 
> FROM app_servicetypecategory 
> WHERE app_servicetypecategory.id IN (1, 2)
>
> Question is: How can I make to run just 2 queries in total? (The last 2 
> queries should be joined with INNER JOIN and a group by per 
> service_type_category_name)
>
> Thanks in advance!
>

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


Re: Using proxy kind of Table in Admin Interface

2015-03-02 Thread Simon Charette
Hi Rootz,

Unfortunately there's a long standing ticket to solve inconsistency with 
permissions for proxy models  so 
your chosen approach won't work until this is fixed.

Simon

Le lundi 2 mars 2015 11:16:36 UTC-5, Rootz a écrit :
>
> Question.
> How would one go about designing the django table(s) so that I can assign 
> each user account/group a different Model Manager using the same table in 
> the Django admin interface? 
>
> After doing some reading the closest that comes to this is the Proxy Model 
> but I tried adding the proxy model manually into the django admin and I got 
> it to work. However when I try to assign permission to each user account 
> for the different proxy models I had created I am only  see only one proxy 
> model in the permission list (django admin interface).
>
> My goal is to create one table that returns a custom QuerySet unique to a 
> user group or user account. Adding to this I would like for this to be 
> visible in the admin interface. Can you guide me as to how can achieve this.
>
> 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/56f0912c-c3f1-4527-a080-e5fa14a41710%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Prefetching a single item

2015-03-02 Thread Simon Charette
Can your seats be part of multiple trains?

Is there a reason you defined a ManyToMany from Train to Seat instead of a 
ForeignKey from Seat to Train?

If your schema was defined as the latter the following could probably work 
(given you only want the first Seat of each Train object):

trains = 
Train.objects.prefetch_related(first_seats=Seat.objects.order_by('train', 
'order').distinct('train'))
for train in trains:
first_seat = train.first_seats[0]

Else given you've explicitly defined a TrainSeat model to handle the 
through relationship to store the order:

class TrainSeat(models.Model):
train = models.ForeignKey(Train, related_name='train_seats')
seat = models.ForeignKey(Seat)
order = models.PositiveIntegerField()

trains = 
Train.objects.prefetch_related(first_train_seats=Prefetch('train_seats', 
TrainSeat.objects.select_related('seat').order_by('train', 
'order').distinct('train'))
for train in trains:
first_seat = train.first_train_seats[0].seat

Hope it helps.

Simon

Le lundi 2 mars 2015 17:23:29 UTC-5, cool-RR a écrit :
>
> Hi,
>
> Say that I have a model Train and it has a ManyToMany to model Seat. I'm 
> looking at a queryset of Train and I want to do a prefetch_related on it, 
> but I don't want to get all the Seat objects; I want only the first Seat 
> object for each Train object.  Is this possible with prefetch_related 
> and/or Prefetch? How? 
>
> To clarify: My goal here is to save on querysets while still being able to 
> retrieve the first Seat object in each `train.seats`.
>
>
> Thanks,
> Ram.
>

-- 
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/b3fcf574-9024-46f9-9499-c6e67d2e3a4b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django OperationalError

2015-03-02 Thread Petar Pilipovic
Hello James, sorry for not uploading mine answer on this mater, I was busy 
whit something else this day, ok now back to mine Operational Error I have 
got.
I tried to google some solution to this problem had no luck, and I did what 
have you told me.
I heave done some 
python manage.py sqlflush

and that has gave me this output: 

(django17)04:20 ~/mineDjango$ python manage.py sqlflush BEGIN;DELETE FROM 
"django_admin_log";DELETE FROM "auth_permission";DELETE FROM "auth_group";
DELETE FROM "auth_group_permissions";DELETE FROM "django_session";DELETE 
FROM "auth_user_groups";DELETE FROM "auth_user_user_permissions";DELETE FROM 
"account_emailaddress";DELETE FROM "django_site";DELETE FROM 
"profiles_profile";DELETE FROM "auth_user";DELETE FROM "profiles_userstripe"
;DELETE FROM "account_emailconfirmation";DELETE FROM "django_content_type";
COMMIT;

Then I have done 
python manage.py syncdb python manage.py migrate

Output of mine recreating tables are this:
(django17)04:20 ~/mineDjango$ python manage.py syncdbOperations to perform: 
Synchronize unmigrated apps: allauth, crispy_forms Apply all migrations: 
account, 
sessions, admin, sites, profiles, contenttypes, authSynchronizing apps 
without migrations: Creating tables... Installing custom SQL... Installing 
indexes...Running migrations: No migrations to apply.(django17)04:20 
~/mineDjango$ python manage.py migrateOperations to perform: Synchronize 
unmigrated apps: allauth, crispy_forms Apply all migrations: account, 
sessions, admin, sites, profiles, contenttypes, authSynchronizing apps 
without migrations: Creating tables... Installing custom SQL... Installing 
indexes...Running migrations: No migrations to apply.
Basically I have had no changes in mine attempt to drop and recreate tables 
in mine application.
The error is still there.
Error:
Environment:




Request Method: GET
Request URL: http://copser.pythonanywhere.com/


Django Version: 1.7.2
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'profiles',
 'crispy_forms',
 'django.contrib.sites',
 'allauth',
 'allauth.account',
 'stripe')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')




Template error:
In template /home/copser/static/templates/home.html, error at line 40
   no such table: django_session
   30 :  




   31 : {% block content %}




   32 :  




   33 : 




   34 :   




   35 : 




   36 : 




   37 :  {##}




   38 :




   39 : 




   40 :  {% if request.user.is_authenticated %} 




   41 : Hello {{ request.user }}




   42 : {% else %}




   43 :   




   44 :  {% csrf_token %}




   45 : 




   46 : Login* 





   47 : Password* 




   48 : Remember Me




   49 : 




   50 : 




Traceback:
File 
"/home/copser/.virtualenvs/django17/local/lib/python2.7/site-packages/django/core/handlers/base.py"
 
in get_response
  111. response = wrapped_callback(request, 
*callback_args, **callback_kwargs)
File "/home/copser/mineDjango/profiles/views.py" in home
  7. return render(request, template, context)
File 
"/home/copser/.virtualenvs/django17/local/lib/python2.7/site-packages/django/shortcuts.py"
 
in render
  48. return HttpResponse(loader.render_to_string(*args, **kwargs),
File 
"/home/copser/.virtualenvs/django17/local/lib/python2.7/site-packages/django/template/loader.py"
 
in render_to_string
  174. return t.render(context_instance)
File 
"/home/copser/.virtualenvs/django17/local/lib/python2.7/site-packages/django/template/base.py"
 
in render
  148. return self._render(context)
File 
"/home/copser/.virtualenvs/django17/local/lib/python2.7/site-packages/django/template/base.py"
 
in _render
  142. return self.nodelist.render(context)
File 
"/home/copser/.virtualenvs/django17/local/lib/python2.7/site-packages/django/template/base.py"
 
in render
  844. bit = self.render_node(node, context)
File 
"/home/copser/.virtualenvs/django17/local/lib/python2.7/site-packages/django/template/debug.py"
 
in render_node
  80. return node.render(context)
File 
"/home/copser/.virtualenvs/django17/local/lib/python2.7/site-packages/django/template/loader_tags.py"
 
in render
  126. return compiled_parent._render(context)
File 
"/home/copser/.virtualenvs/

Re: Complex Querys And Results Response Processing/Formatting

2015-03-02 Thread James Schneider
So, do objects ever get successfully added to the list? I had a bit of
trouble following your workflow and figuring out where your issue actually
lives.

When you say 'send the final list back to an HTML page' do you mean the
Django process is generating the HTML and sending it back as a response to
an AJAX request, or do you mean that Django is responding with a serialized
JSON response, and your JavaScript will handle the HTML formatting of that
data?

If the former, I would assume that your JS would not need to parse the HTML
returned from the server and would just insert it somewhere into the page
that the user is currently viewing.

If the latter, are you formatting/serializing the data as JSON yourself? Or
are you serializing it into JSON using the usual Django methods?



Beyond that, what errors are you seeing and where?


-James


On Mon, Mar 2, 2015 at 10:56 AM, Henry Versemann 
wrote:

> I'm trying to submit a series of ajax requests from some server code. When
> I get a response back from each request I'm trying to add that response to
> a list.
> Once all of the requests have been sent and all of their responses
> received and added to the list, then I want to send the final list back to
> an html page for viewing by a user.
> My problem is I can't seem to get the JSON formatting correct either
> before I add each piece of response data to the list, or right before I
> return the list in my HttpResponse so then when it gets sent back to the
> client page my jQuery/javascript cannot parse the data correctly and it
> fails.
>
> Any help would be greatly appreciated.
>
> Thanks.
>
> Henry
>
>
> --
> 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/ec9be9f3-dd43-4c5c-8649-32c27eb01998%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/CA%2Be%2BciUYb8Gq3yGBYdhC_U1-MSFximWamiR%2BE5MpR5Mx%3DbE%2B_w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Prefetching a single item

2015-03-02 Thread cool-RR
Hi,

Say that I have a model Train and it has a ManyToMany to model Seat. I'm 
looking at a queryset of Train and I want to do a prefetch_related on it, 
but I don't want to get all the Seat objects; I want only the first Seat 
object for each Train object.  Is this possible with prefetch_related 
and/or Prefetch? How? 

To clarify: My goal here is to save on querysets while still being able to 
retrieve the first Seat object in each `train.seats`.


Thanks,
Ram.

-- 
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/1d6fc84a-2042-40b5-98be-40bd971e706c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Traversing relationships based on lookup strings

2015-03-02 Thread James Schneider
Whoops, I meant to swap out 'item' for 'instance' to make it a bit more
readable, but got myself distracted and forgot to finish and hit send.

So, s/item/instance/...

HTH,

-James

On Mon, Mar 2, 2015 at 2:11 PM, James Schneider 
wrote:

> Nothing in Django specifically that I'm aware of (although that's not
> saying much), but you can probably do something pretty slick with the
> operator library and attrgetter:
>
> https://docs.python.org/2/library/operator.html#operator.attrgetter
>
> It would probably look something like this (untested):
>
>
> # define a function to pull the nested attribute
> # assume this is in myapp/utils.py
> def get_item_attr(obj_instance, search_string):
> dotted_string = search_string.replace('__', '.')
> instance_attr = operator.attrgetter(dotted_string)
> instance_attr_value = instance_attr(obj_instance)
> return item_attr_value
>
>
> # later, in a view, maybe...
> from myapp.utils import get_item_attr
> booking_client_name = get_item_attr(trip, 'booking__client__name')
>
>
> Obviously this is naive and you'll need to check for failures at various
> points and raise some exceptions if attributes can't be found/accessed, but
> I think this may point you in the right direction.
>
> Never tried this on my own so YMMV. Note that you'll incur multiple DB
> hits using a function like this (for the FK traversals), so be careful if
> you plan to run such a function several times for a single request.
>
> -James
>
>
> On Mon, Mar 2, 2015 at 10:54 AM, Francis Devereux 
> wrote:
>
>> Hi,
>>
>> Is there a Django function that takes a model instance and a lookup
>> string, and returns the value of the related field?
>>
>> For example:
>>
>> the_function_i_am_looking_for(trip, 'booking__client__name')
>>
>> would return the same as:
>>
>> trip.booking.client.name
>>
>> Thanks,
>>
>> Francis
>>
>> --
>> 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/FB0F25B1-00B0-4CD5-A62D-B9CE44F189C8%40devrx.org
>> .
>> 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/CA%2Be%2BciVF5r2cqguM%2BLfOXT0x32ZncseAbOYOpfsQaPeLEROfgQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Traversing relationships based on lookup strings

2015-03-02 Thread James Schneider
Nothing in Django specifically that I'm aware of (although that's not
saying much), but you can probably do something pretty slick with the
operator library and attrgetter:

https://docs.python.org/2/library/operator.html#operator.attrgetter

It would probably look something like this (untested):


# define a function to pull the nested attribute
# assume this is in myapp/utils.py
def get_item_attr(obj_instance, search_string):
dotted_string = search_string.replace('__', '.')
instance_attr = operator.attrgetter(dotted_string)
instance_attr_value = instance_attr(obj_instance)
return item_attr_value


# later, in a view, maybe...
from myapp.utils import get_item_attr
booking_client_name = get_item_attr(trip, 'booking__client__name')


Obviously this is naive and you'll need to check for failures at various
points and raise some exceptions if attributes can't be found/accessed, but
I think this may point you in the right direction.

Never tried this on my own so YMMV. Note that you'll incur multiple DB hits
using a function like this (for the FK traversals), so be careful if you
plan to run such a function several times for a single request.

-James


On Mon, Mar 2, 2015 at 10:54 AM, Francis Devereux  wrote:

> Hi,
>
> Is there a Django function that takes a model instance and a lookup
> string, and returns the value of the related field?
>
> For example:
>
> the_function_i_am_looking_for(trip, 'booking__client__name')
>
> would return the same as:
>
> trip.booking.client.name
>
> Thanks,
>
> Francis
>
> --
> 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/FB0F25B1-00B0-4CD5-A62D-B9CE44F189C8%40devrx.org
> .
> 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/CA%2Be%2BciWP%2BZ9A_D%3DCxrPfgoUVZEtN3FLWe_eQSmpwN7eD9sJrFw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Traversing relationships based on lookup strings

2015-03-02 Thread Francis Devereux
Hi,

Is there a Django function that takes a model instance and a lookup string, and 
returns the value of the related field?

For example:

the_function_i_am_looking_for(trip, 'booking__client__name')

would return the same as:

trip.booking.client.name

Thanks,

Francis

-- 
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/FB0F25B1-00B0-4CD5-A62D-B9CE44F189C8%40devrx.org.
For more options, visit https://groups.google.com/d/optout.


Complex Querys And Results Response Processing/Formatting

2015-03-02 Thread Henry Versemann
I'm trying to submit a series of ajax requests from some server code. When 
I get a response back from each request I'm trying to add that response to 
a list.
Once all of the requests have been sent and all of their responses received 
and added to the list, then I want to send the final list back to an html 
page for viewing by a user.
My problem is I can't seem to get the JSON formatting correct either before 
I add each piece of response data to the list, or right before I return the 
list in my HttpResponse so then when it gets sent back to the client page 
my jQuery/javascript cannot parse the data correctly and it fails.

Any help would be greatly appreciated.

Thanks.

Henry


-- 
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/ec9be9f3-dd43-4c5c-8649-32c27eb01998%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Using proxy kind of Table in Admin Interface

2015-03-02 Thread Rootz
Ok below is a sample of the models.py


class LocationProfile(models.Model):
shortName = models.CharField('Location Name',max_length=100,primary_key 
= True)
longName = models.CharField('Church Name',max_length=100)
.

class Member(models.Model):
first = models.CharField('First Name',max_length=150)
last =  models.CharField('Last Name',max_length=150)
.

###Meadowvale SDA
###Model Manager 
class MeadowvaleManager(models.Manager):
def get_queryset(self):
return super(MeadowvaleManager, self).get_queryset().filter(
churchLoc='meadow-sda')


###Model Proxy
class MeadowvaleMember(Member):
objects = MeadowvaleManager()

class Meta:
verbose_name = "MeadowMember"
proxy = True



Another SDA
###Model Manager
class AnotherManager(models.Manager):
def get_queryset(self):
return super(AnotherManager, self).get_queryset().filter(id=1)


###Model Proxy
class AnotherMember(Member):
objects = AnotherManager()

class Meta:
verbose_name = "AnotherMember"
proxy = True



below is a sample of the admin.py

from members.mymodels.models import MeadowvaleMember,AnotherMember
  
class MeadowvaleMemberAdmin(admin.ModelAdmin):
def get_query_set(self,request):
return MeadowvaleMember.objects.all()


class AnotherMemberAdmin(admin.ModelAdmin):
def get_query_set(self,request):
return AnotherMember.objects.all()

#proxy

admin.site.register(MeadowvaleMember,MeadowvaleMemberAdmin)
admin.site.register(AnotherMember,AnotherMemberAdmin)


On Monday, March 2, 2015 at 12:21:47 PM UTC-5, Derek wrote:
>
> I am not quite sure what you are trying to achieve (without seeing sample 
> code), but here is some very basic code showing how a proxy could work:
>
> models.py
>
> class MainModel(Model):
>"""mother of models"""
> ...
> 
>
> class MainModelProxy(MainModel):
> objects = MainModelProxyManager()
>
> class Meta:
> proxy = True
>
>
> admin.py
>
> class MainModelAdmin(ModelAdmin):
> """mother of all admin"""
> ...
>
>
> class MainModelProxyAdmin(MainModelAdmin):
> #add salt to taste
> 
>
> admin.site.register(MainModel, MainModelAdmin)
> admin.site.register(MainModelProxy, MainModelProxyAdmin)
>
>
> On Monday, 2 March 2015 18:16:36 UTC+2, Rootz wrote:
>>
>> Question.
>> How would one go about designing the django table(s) so that I can assign 
>> each user account/group a different Model Manager using the same table in 
>> the Django admin interface? 
>>
>> After doing some reading the closest that comes to this is the Proxy 
>> Model but I tried adding the proxy model manually into the django admin and 
>> I got it to work. However when I try to assign permission to each user 
>> account for the different proxy models I had created I am only  see only 
>> one proxy model in the permission list (django admin interface).
>>
>> My goal is to create one table that returns a custom QuerySet unique to a 
>> user group or user account. Adding to this I would like for this to be 
>> visible in the admin interface. Can you guide me as to how can achieve this.
>>
>> 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/19bc578f-1704-4a58-a068-13b89139c859%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Using proxy kind of Table in Admin Interface

2015-03-02 Thread Derek
I am not quite sure what you are trying to achieve (without seeing sample 
code), but here is some very basic code showing how a proxy could work:

models.py

class MainModel(Model):
   """mother of models"""
...


class MainModelProxy(MainModel):
objects = MainModelProxyManager()

class Meta:
proxy = True


admin.py

class MainModelAdmin(ModelAdmin):
"""mother of all admin"""
...


class MainModelProxyAdmin(MainModelAdmin):
#add salt to taste


admin.site.register(MainModel, MainModelAdmin)
admin.site.register(MainModelProxy, MainModelProxyAdmin)


On Monday, 2 March 2015 18:16:36 UTC+2, Rootz wrote:
>
> Question.
> How would one go about designing the django table(s) so that I can assign 
> each user account/group a different Model Manager using the same table in 
> the Django admin interface? 
>
> After doing some reading the closest that comes to this is the Proxy Model 
> but I tried adding the proxy model manually into the django admin and I got 
> it to work. However when I try to assign permission to each user account 
> for the different proxy models I had created I am only  see only one proxy 
> model in the permission list (django admin interface).
>
> My goal is to create one table that returns a custom QuerySet unique to a 
> user group or user account. Adding to this I would like for this to be 
> visible in the admin interface. Can you guide me as to how can achieve this.
>
> 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/bef0acd2-3a6b-4c61-b3f8-70e55e46d7d2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Python / Django slow ? Deciding my next technological stack

2015-03-02 Thread Nikolas Stevenson-Molnar

On 3/1/2015 7:13 AM, Benj wrote:
Just a little questions guys: when a user upload a file to server, and 
that file is a litte big and takes 3 seconds to be uploaded... what's 
the proper way, if possible, not to block the entire system for these 
3 seconds so the server can serve other users while the upload is 
taking place.
Let a web server handle the actual upload. Nginx is really good at this, 
it can easily handle thousands of concurrent connections. Once all the 
data is actually transferred to the server, only then does the request 
get passed on to your Django app. A worker is not needed until that 
point. This is the default behavior if you use a Nginx / Gunicorn (or 
uWSGI) / Django stack.


You can also use the Nginx Upload Module, and your Django app will never 
need to receive the actual data at all. Nginx will handle the upload, 
put it in a location of your choosing, then hand the path on the server 
off to your app. http://wiki.nginx.org/HttpUploadModule


_Nik

--
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/54F48FE7.2030103%40consbio.org.
For more options, visit https://groups.google.com/d/optout.


Using proxy kind of Table in Admin Interface

2015-03-02 Thread Rootz
Question.
How would one go about designing the django table(s) so that I can assign 
each user account/group a different Model Manager using the same table in 
the Django admin interface? 

After doing some reading the closest that comes to this is the Proxy Model 
but I tried adding the proxy model manually into the django admin and I got 
it to work. However when I try to assign permission to each user account 
for the different proxy models I had created I am only  see only one proxy 
model in the permission list (django admin interface).

My goal is to create one table that returns a custom QuerySet unique to a 
user group or user account. Adding to this I would like for this to be 
visible in the admin interface. Can you guide me as to how can achieve this.

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/5f24f7fc-4865-477d-83fe-bb9f98e23189%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Populating Django app db with JSON data

2015-03-02 Thread aRkadeFR

“custom Python code in a historical context”
FMPOV, it means that your code will be run exactly at a certain
schema of your DB. If your migration is the 3rd one, it will
always be run after your first two migrations, thus you will
know exactly your schema.

The schema is passed to your function (as apps and schema_editor)
in order to get your Model class.

Sorry if my explanation wasn't clear, hope it will help at least.

On 03/02/2015 10:27 AM, Murthy Sandeep wrote:

Hi

thanks for the info.

The docs also say that RunPython runs “custom Python code
in a historical context”.  What does that mean exactly?  It seems
related to the apps and schema_editor arguments passed to
the custom method that will be called by RunPython - is this something
like a snapshot of the app model that is stored when I do `python manage.py 
migrate`?

Sandeep



On 2 Mar 2015, at 19:37, aRkadeFR  wrote:

Hello,

Indeed, the data migration is the best way. Check out
the documentation here:
https://docs.djangoproject.com/en/1.7/ref/migration-operations/#django.db.migrations.operations.RunPython

You write your function that will be called by the RunPython
and will load your JSON.
Migration are ordered, your first migration will create the
tables and the second (your data migration) will load your
JSON.

To create an empty migration:
./manage.py makemigrations  --empty

You can rename to a useful descriptive name the migration
file.

Have a good one


On 03/02/2015 08:16 AM, Sandeep Murthy wrote:

Hi

I've tried to get the answer to this question (which is a bit open-ended) on 
stackoverflow without much success, which
is basically this: what is the recommended approach to populating a 
pre-existing Django app database table (generated
from a model and which is currently empty) with JSON data?

There seem to be several alternatives given in the Django documentation (Django 
1.7 manual) which include (1) fixtures,
(2) SQL scripts, (3) data migrations.  Of these I am a bit confused by the 
advice in the manual which suggests that (1)
and (2) are only useful for loading initial data.  That's not what I want to 
do.  The data that the app needs is going to be
persistent and permanent because the app is intended to be a web query tool for 
a large dataset that is currently in the
form of several JSON files, each containing on average thousands of JSON 
objects, each object representing an entry
corresponding to a table entry in a relational db.  The data is not going to be 
re-loaded or change after entry, and there
is no user facility for changing the data.

The table has been created using the makemigrations and migrate tools, but is 
empty.  I just need to populate the
table with the JSON data.  It seems that I need to write a custom data 
migration script that will insert the data into the
table via the interpreter, and then I need to run python manage.py migrate.  Is 
this the case, and if so, are there
are examples that I could use?

Thanks in advance for any suggestions.

SM
--
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/db5919c5-ace4-4556-b90e-aa47baa26552%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/54F42164.6040505%40arkade.info.
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/54F43A59.60803%40arkade.info.
For more options, visit https://groups.google.com/d/optout.


Re: Melb Django School Second GO

2015-03-02 Thread Lachlan Musicman
Long time on and off list member. I went to the first round of classes
and would recommend. Very comfortable space, training leaders knew
their Django v well.

L.
--
"This is a profound psychological violence here. How can one even
begin to speak of dignity in labor when one secretly feels one's job
should not exist?"

On the Phenomenon of Bullshit Jobs, David Graeber
http://strikemag.org/bullshit-jobs/


On 2 March 2015 at 15:17, MelbDjango School  wrote:
> Hey Guys,
>
> Melb Django & Common Code is starting its second round of free classes on
> Django. The classes are going to be held fortnightly starting March 12 from
> 4-6pm. They will be going through the essentials of Django to advance
> topics. The course will be given by leading Django Developers in the
> industry. Please bring a laptop and we'll provide the rest. See you in
> School!
>
> If you have any questions please contact
> melbdjangosch...@acommoncreative.com.
>
> Cheers,
> Darren
>
> --
> 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/b39acf36-3a9f-411d-8aff-a172c8bfa754%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/CAGBeqiPe7bSvKDNpOZ6Yu_dDbDmEpqM85vcyBQ%2BwgyD8Q9LcJg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Populating Django app db with JSON data

2015-03-02 Thread aRkadeFR

Hello,

Indeed, the data migration is the best way. Check out
the documentation here:
https://docs.djangoproject.com/en/1.7/ref/migration-operations/#django.db.migrations.operations.RunPython

You write your function that will be called by the RunPython
and will load your JSON.
Migration are ordered, your first migration will create the
tables and the second (your data migration) will load your
JSON.

To create an empty migration:
./manage.py makemigrations  --empty

You can rename to a useful descriptive name the migration
file.

Have a good one


On 03/02/2015 08:16 AM, Sandeep Murthy wrote:

Hi

I've tried to get the answer to this question (which is a bit 
open-ended) on stackoverflow without much success, which
is basically this: what is the recommended approach to populating a 
pre-existing Django app database table (generated

from a model and which is currently empty) with JSON data?

There seem to be several alternatives given in the Django 
documentation (Django 1.7 manual) which include (1) fixtures,
(2) SQL scripts, (3) data migrations.  Of these I am a bit confused by 
the advice in the manual which suggests that (1)
and (2) are only useful for loading initial data.  That's not what I 
want to do.  The data that the app needs is going to be
persistent and permanent because the app is intended to be a web query 
tool for a large dataset that is currently in the
form of several JSON files, each containing on average thousands of 
JSON objects, each object representing an entry
corresponding to a table entry in a relational db.  The data is not 
going to be re-loaded or change after entry, and there

is no user facility for changing the data.

The table has been created using the makemigrations and migratetools, 
but is empty.  I just need to populate the
table with the JSON data.  It seems that I need to write a custom data 
migration script that will insert the data into the
table via the interpreter, and then I need to run python manage.py 
migrate.  Is this the case, and if so, are there

are examples that I could use?

Thanks in advance for any suggestions.

SM
--
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/db5919c5-ace4-4556-b90e-aa47baa26552%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/54F42164.6040505%40arkade.info.
For more options, visit https://groups.google.com/d/optout.


Re: i have a question ,whether Django’s cache framework can support transparent proxy deploy mode at isp environment ?

2015-03-02 Thread Avraham Serour
I don't see how they are related, each is on a different layer

The final user will request a page from the ISP, it may get from its own
cache (squid) or request from your django server.

Your django server will produce the response, it may get it from its own
cache (memcached) or process it

So in case squid decides to respond from its own cache, django will never
see the request

On Mon, Mar 2, 2015 at 8:48 AM, 'johnzeng' via Django users <
django-users@googlegroups.com> wrote:

>
> Hello All :
>
> i have a question , if possible , hope to get your advisement
>
> whether Django’s cache framework can support transparent proxy at isp
> environment ?
>
> and our goal is Django’s cache framework ( middle cache layer ) + Squid (
> transparent proxy mode ) at isp environment ?
>
>
> although i read the detail , but i can't confirm whether Django’s cache
> framework can support transparent proxy deploy mode
>
> https://docs.djangoproject.com/en/1.7/topics/cache/
>
>
>
>Downstream caches¶
>
>
> So far, this document has focused on caching your /own/ data. But another
> type of caching is relevant to Web development, too: caching performed by
> “downstream” caches. These are systems that cache pages for users even
> before the request reaches your Web site.
>
> Here are a few examples of downstream caches:
>
>  * Your ISP may cache certain pages, so if you requested a page from
>http://example.com/, your ISP would send you the page without having
>to access example.com directly. The maintainers of example.com have
>no knowledge of this caching; the ISP sits between example.com and
>your Web browser, handling all of the caching transparently.
>  * Your Django Web site may sit behind a /proxy cache/, such as Squid
>Web Proxy Cache (http://www.squid-cache.org/), that caches pages for
>performance. In this case, each request first would be handled by
>the proxy, and it would be passed to your application only if needed.
>  * Your Web browser caches pages, too. If a Web page sends out the
>appropriate headers, your browser will use the local cached copy for
>subsequent requests to that page, without even contacting the Web
>page again to see whether it has changed.
>
> Downstream caching is a nice efficiency boost, but there’s a danger to it:
> Many Web pages’ contents differ based on authentication and a host of other
> variables, and cache systems that blindly save pages based purely on URLs
> could expose incorrect or sensitive data to subsequent visitors to those
> pages.
>
> For example, say you operate a Web email system, and the contents of the
> “inbox” page obviously depend on which user is logged in. If an ISP blindly
> cached your site, then the first user who logged in through that ISP would
> have their user-specific inbox page cached for subsequent visitors to the
> site. That’s not cool.
>
> Fortunately, HTTP provides a solution to this problem. A number of HTTP
> headers exist to instruct downstream caches to differ their cache contents
> depending on designated variables, and to tell caching mechanisms not to
> cache particular pages. We’ll look at some of these headers in the sections
> that follow.
>
>
>
> --
> 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/54F407CD.2030403%40yahoo.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/CAFWa6tLjLcixbsx1f4pRBDDUMViodGua0YugHaoezhA%3DVOOvuA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.