Re: update() (for bulks) is a atomic operation?

2009-10-25 Thread Mikhail Korobov

Yes, it's a single query.

Take a look at django-debug-toolbar. It can display all SQL queries
that was executed during request/response so you'll always be sure
what's going on.

On 26 окт, 03:12, wancharle sebastiao quirino 
wrote:
> Hello,
>
> I currently am using raw sql to make an atomic operation of the following :
>
> UPDATE table SET field1 = 0, flag = 'A' WHERE flag = 'I'
>
> Reading the documentation I realized I could do this:
>
> Table.objects.filter(flag='I').update(field1=0,flag='A')
>
> I want to make sure that this is a unique operation. (to avoid problems of
> parallelism and concurrency)
>
> Someone could confirm me this? Apparently the limitations imposed by the
> documentation already gives a hint that is a single query but I want to be
> sure.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Admin interface is doing nothing

2009-10-26 Thread Mikhail Korobov

It is very likely that your urls.py is wrong. Re-check if admin urls
are included exactly as in documentation example: "(r'^admin/', include
(admin.site.urls))", without any wildcards.

On 27 окт, 00:12, "M."  wrote:
> Hi,
>
> I've installed the Admin interface, but the interface is unresponsive.
> If click on USERS, the page refreshes itself and appends auth/user/ to
> the URL. If I click it again, it appends it again, but I still remain
> on the same page. I am using Python 2.6 and Ubuntu.
>
> Thanks,
> Martynas
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Adding button to admin change form

2009-10-26 Thread Mikhail Korobov

You should override change_form.html template and save it as

/your_project/templates/admin/your_app/change_form.html

or

/your_project/templates/admin/your_app/your_model/change_form.html

On 26 окт, 21:45, Aaron  wrote:
> I need to add a button to the admin change form of certain models,
> which would be placed among the save buttons. I've tried overriding
> the template submit_line.html, but I am coming under the impression
> that this is not possible unless I override the template for my entire
> project.
>
> I need this button so that I can write a view or some other kind of
> handler that is able to access the model form contained in the admin
> change form page. If using the button, I'd override the add_view and
> change_view methods of the appropriate ModelAdmin, and do something
> special if "_mybutton" is in the POST data. If adding a button to the
> change form is not possible, is it possible to add some other link to
> the page that would allow me to access the form object?
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Filtering on model methods

2009-10-27 Thread Mikhail Korobov

If you want to be able to sort by some python method you have to fetch
ALL data from all tables that are used in this method. It is indeed a
bad practice and so it is not encouraged in django.

The best you can do is to put your code to model's manager as a
method. Model managers are often used for storing common queries and
some python logic.

Then you'll be able to write something like

results = Person.objects.compare_to_others(gte=1).order_by
('compare_to_others')


On 28 окт, 02:30, pbzRPA  wrote:
> Sorry I would also like to add that I would like to sort by this field
> in generic views. So results = Person.objects.filter
> (compare_to_others__gte = 1).order_by('compare_to_others')
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Filtering on model methods

2009-10-28 Thread Mikhail Korobov

Maybe I wrote a reply without undersanding what you need.

You have 2 separate issues:

1. Want to sort and filter by calculated field
2. Want to create calculated field that is calculated in python

Am I correct?

1) can be acheived using ".extra" method or aggregations

http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none
http://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-by

q = Entry.objects.extra(select={'is_recent': "pub_date >
'2006-01-01'"})
q = q.extra(order_by = ['-is_recent'])

Book.objects.annotate(num_authors=Count('authors')).order_by
('num_authors')

2) is not directly possible because there is no support for this on DB
level. Maybe if you provide exact python code you want it becomes
clear how to solve this.


On 28 окт, 15:39, pbzRPA  wrote:
> Thanks for you reply Mikhail,
>
> I do use model managers but more often to get a certain defined
> queryset back. Could you maybe show me a simple example of how to
> implement your suggestion?
>
> I imagine it looking something like this.
>
> class PersonManager(models.Manager):
>      def get_query_set(self):
>           ??? x = 1
>           return super(type(self), self).get_query_set()
>
> class Person(models.Model):
>     name = models.CharField(...)
>
>     objects = models.Manager()
>     compare_to_other = PersonManager()
>
> Now without pulling the value out of the SQL database how do I add a
> value?
>
> The ?? is where I am not sure of how to define a variable per sql
> line.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Filtering on model methods

2009-10-28 Thread Mikhail Korobov

I think if your methods are really complex then the best you can do is
to denormalise your DB.

Make your calculated fields real fields in a table and update them in
model's save method or using signals.
Another way is to make them calculated by DB using triggers or DB
views but I would prefer denormalisation in this case.

If your methods are not that complex then it may be better to write
manager's methods and put query constructing there.

There are several django apps that can help with denormalisation
(http://bitbucket.org/daevaorn/django-composition/src/,
http://github.com/initcrash/django-denorm).

On 28 окт, 19:29, pbzRPA  wrote:
> I think my problem is both 1 and 2. What happens when you want to use
> python modules to analyse the extra field?
>
> For Example:
>
> Database table History:
>     id       |  Ordered | Delivered | Invoiced |
>     1              10           15           5
>     2               5            5            3
>
> class History(models.Model):
>     ordered = models.IntegerField()
>     delivered = models.IntegerField()
>     Invoiced = models.IntegerField()
>
>     def compute_problem(self):
>          'here will be code that analyses the above data'
>          if self.ordered > self.delivered:
>              return self.ordered - self.delivered
>          if self.invoiced < self.delivered:
>              return self.delivered - self.invoiced
>          return 0
>
> Ideally I would like to create the virtual scenario:
>
>     id       |  Ordered | Delivered | Invoiced | compute_problem
>     1              10           15           5               -5
>     2               5            5            3               -2
>
> in the view I would like to do the following. Please note that my
> compute_problem is a real basic example and I am sure that the above
> example I could do in SQL but my methods become a lot more
> complicated.
>
> queryset = History.objects.filter().exclude(compute_problem = 0)
>
> I can not modify the database as I am writing add-ons and not creating
> the database myself.
>
> I hope this makes a bit more sense. :)
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Performance monitoring

2009-12-09 Thread Mikhail Korobov
Performance monitoring doesn't have to be related to django itself.
There are external projects that cant do performance monitoring (CPU,
i/o, memory usage over time). You may give munin (http://
munin.projects.linpro.no/) a chance.

On Dec 10, 7:43 am, Kegan Gan  wrote:
> Hi,
>
> Google App Engine provides a rather extensive set of tools to monitor
> the performance of your applications running in App Engine. Is there
> something similar for Django?
>
> Thanks.

--

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




Re: Saving a location with a model

2010-08-30 Thread Mikhail Korobov
You may find this useful: http://bitbucket.org/barttc/django-generic-location

On 31 авг, 04:05, Joel Klabo  wrote:
> I want to tie a location to each instance of a model. I am planning on
> getting the lat/long. from navigator.geolocation through javascript.
> My original idea is to have a location model with fields, latitude,
> longitude, and the id of whatever model it is linked to. Is that the
> way to go? Anyone have experience with this?

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



Re: How to aggregate values by month

2010-10-28 Thread Mikhail Korobov
Hi Rogério,

You can give http://bitbucket.org/kmike/django-qsstats-magic/src a
try.
It currently have efficient aggregate lookups (1 query for the whole
time series) only for mysql but it'll be great if someone contribute
efficient lookups for other databases :)

On 28 окт, 19:31, Rogério Carrasqueira
 wrote:
> Hello!
>
> I'm having an issue to make complex queries in django. My problem is, I have
> a model where I have the sales and I need to make a report showing the sales
> amount per month, by the way I made this query:
>
> init_date = datetime.date(datetime.now()-timedelta(days=365))
> ends_date = datetime.date(datetime.now())
> sales =
> Sale.objects.filter(date_created__range=(init_date,ends_date)).values(date_ 
> created__month).aggregate(total_sales=Sum('total_value'))
>
> At the first line I get the today's date past one year
> after this I got the today date
>
> at sales I'm trying to between a range get the sales amount grouped by
> month, but unfortunatelly I was unhappy on this, because this error
> appeared:
>
> global name 'date_created__month' is not defined
>
> At date_created is the field where I store the information about when the
> sale was done., the __moth was a tentative to group by this by month.
>
> So, my question: how to do that thing without using a raw sql query and not
> touching on database independence?
>
> Thanks so much!
>
> Rogério Carrasqueira
>
> ---
> e-mail: rogerio.carrasque...@gmail.com
> skype: rgcarrasqueira
> MSN: rcarrasque...@hotmail.com
> ICQ: 50525616
> Tel.: (11) 7805-0074

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



Re: How to aggregate values by month

2010-11-04 Thread Mikhail Korobov
Hi Rogério!

With django-qsstats-magic it would be something like this:

stats = QuerySetStats(Sale.objects.all(), 'date_created')
totals = stats.time_series(start, end, 'months',
aggregate=Sum('total_value'))
averages = stats.time_series(start, end, 'months',
aggregate=Avg('total_value'))

Great you've found the solution without any plugins!


On 3 ноя, 23:44, Rogério Carrasqueira 
wrote:
> Hi Mikhail!
>
> Can you give some clue on how to use your plugin considering my scenario?
>
> Thanks
>
> Rogério Carrasqueira
>
> ---
> e-mail: rogerio.carrasque...@gmail.com
> skype: rgcarrasqueira
> MSN: rcarrasque...@hotmail.com
> ICQ: 50525616
> Tel.: (11) 7805-0074
>
> 2010/10/28 Mikhail Korobov 
>
>
>
> > Hi Rogério,
>
> > You can givehttp://bitbucket.org/kmike/django-qsstats-magic/srca
> > try.
> > It currently have efficient aggregate lookups (1 query for the whole
> > time series) only for mysql but it'll be great if someone contribute
> > efficient lookups for other databases :)
>
> > On 28 окт, 19:31, Rogério Carrasqueira
> >  wrote:
> > > Hello!
>
> > > I'm having an issue to make complex queries in django. My problem is, I
> > have
> > > a model where I have the sales and I need to make a report showing the
> > sales
> > > amount per month, by the way I made this query:
>
> > > init_date = datetime.date(datetime.now()-timedelta(days=365))
> > > ends_date = datetime.date(datetime.now())
> > > sales =
>
> > Sale.objects.filter(date_created__range=(init_date,ends_date)).values(date_
> > created__month).aggregate(total_sales=Sum('total_value'))
>
> > > At the first line I get the today's date past one year
> > > after this I got the today date
>
> > > at sales I'm trying to between a range get the sales amount grouped by
> > > month, but unfortunatelly I was unhappy on this, because this error
> > > appeared:
>
> > > global name 'date_created__month' is not defined
>
> > > At date_created is the field where I store the information about when the
> > > sale was done., the __moth was a tentative to group by this by month.
>
> > > So, my question: how to do that thing without using a raw sql query and
> > not
> > > touching on database independence?
>
> > > Thanks so much!
>
> > > Rogério Carrasqueira
>
> > > ---
> > > e-mail: rogerio.carrasque...@gmail.com
> > > skype: rgcarrasqueira
> > > MSN: rcarrasque...@hotmail.com
> > > ICQ: 50525616
> > > Tel.: (11) 7805-0074
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com > groups.com>
> > .
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

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



Re: add template variable to an external view, without changing the view

2010-12-20 Thread Mikhail Korobov
Hi Yves,

In django 1.3 there is also a TemplateResponse (
http://docs.djangoproject.com/en/dev/ref/template-response/ ) that can
perform as render_to_response replacement, doesn't require class based
views and enables developer to change the template context (as well as
the template to be rendered) of a third-party view so the future is
even brighter ;)

It still requires changes to third-party app but the changes are quite
trivial (replacing render_to_response with even simpler
TemplateResponse call) and I expect third-party apps to begin
replacing render_to_response with TemplateResponse or with class based
views once django 1.3 will be released.

In case of registration and login form at the same pages, there are 2
viable solutions:

1. add the login form to context in the context processor (globally or
based on request url);
2. write the html without constructing the form object. This object is
not really necessary because the validation, etc. should be handled by
an another view and django form object is not necessary to make html
form in django.

On 20 дек, 20:00, yves_s  wrote:
> Hello
>
> I'm using the registration django app and want to have the
> registration and login form on the same page.
> When I reuse the auth_login view, the registration form is missing in
> the context of the template.
> My quickfix is to copy the original auth login view to my own views.
> Then I changed the the call of "return render_to_response(..." and
> added the registration form. This works but this approach is not very
> DRY.
>
> I tried other approaches, but nothing worked.
> The first idea was to use a view decorator, but this don't worked
> because the view decorator
> is to late in the chain and already has the finished rendered template
> html code.
>
> The next idea was to import the login view and than to redefine the
> render_to_response function. I only got this working when the login
> view code is in my own views file, so not very DRY.
>
> I tried to make a new "version" of the login view with the python new
> module. The idea was to pass
> a new global context to the login view so that it uses my changed
> render_to_response function.
>
> This was the code:
> loign_new = new.function(login.func_code, globals(), login.func_name,
> login.func_defaults, login.func_closure)
>
> It worked partial, put the registration form was the same as login
> form, so some fields were missing.
>
> In django 1.3 there are are class based view, which solves this issue
> with the function get_context_data, but the external app must uses
> class based views, so the future looks birght :-)
>
> Is there any solution to get this working in django 1.2 with views
> from other apps? Any dirty python tricks?
>
> regards
> Yves

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



Re: Group models by personal order and no by app in admin

2010-12-24 Thread Mikhail Korobov
Hi Alex,

django-admin-tools should solve all your problems with admin index
page.

https://bitbucket.org/izi/django-admin-tools/

On 24 дек, 17:48, Álex González  wrote:
> Hi!
>
> I have a lot of models in same app at my django app, can I group then
> another way that app order?
>
> I see:
>
> Auth
>    Users
>
> Sites
>    Sites
>
> My app
>   Model 1
>   Model 2
>   Model 3
>   ...
>   Model N
>
> And like for example, Model 1&2 under "My app (Users)" tab. and 3 to N in
> "My app (configuration)"
>
> Thanks!
>
> --
> @agonzalezro 
> Please, don't send me files with extensions: .doc, .docx, .xls, .xlsx, .ppt
> and/or .pptx

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



Re: Access to request from tag

2010-12-26 Thread Mikhail Korobov
Hi Igor,

If you use django <= 1.2 the you can replace 'render_to_response' with
'direct_to_template'. They do almost the same but 'direct_to_template'
uses RequestContext by default:

from django.views.generic.simple import direct_to_template

def my_view(request):
# ...
return direct_to_template(request, 'my_template.html', {'foo':
'bar'})

In django trunk there are 2 less hacky shortcuts that can help:

http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render
http://docs.djangoproject.com/en/dev/ref/template-response/#using-templateresponse-and-simpletemplateresponse

On 26 дек, 21:52, Igor Artamonov  wrote:
> BTW, thank you very much.
>
> I googled a lot, and decided that easiest way is replace all my "Context("
> with "RequestContext(request," and use official way.
> That works :)

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



Re: How to get an dictionary item in template

2010-12-26 Thread Mikhail Korobov
production = Production.objects.all()
for product in production:
try:
product.image = product.image_set.get (somefield = somevalue)
except Image.DoesNotExist:
pass

{% for product in production %}
{{ product.title }}

{% endfor %}

or even better implement the 'get_image' method for the Product.

But please note that these solutions are executing SQL queries for
each product. It may be better to denormalize the DB and add a FK
field to Product model pointing to the main Image model.


On 26 дек, 23:56, BigBlogMaker  wrote:
> I'm sorry for my english, but on other groups nobody does not answers.
>
> In view defined variables:
>
> production = Production.objects.all ()
> images = {}
> for product in production:
>     try:
>         image = product.image_set.get (somefield = somevalue)
>         images [product.id] = image
>     except:
>         pass
>
> Now the question is: how to access the elements of images in the
> template?
>
> {% for product in production %}
> {{ product.title }}
> {% if images %}
>  "{{ images..title }}"/>
> {% endif %}
> {% endfor %}

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



Re: how to map admin actions with shortcut keys

2011-01-09 Thread Mikhail Korobov
Hi Rahul,

This can be solved using custom javascript. Override ModelAdmin's
changelist template ( 
http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#overriding-admin-templates
) in order to insert the necessary javascript code.

On 10 янв, 00:37, rahul jain  wrote:
> How to map admin actions with shortcut keys ?
>
> I have an action to perform on rows (objects) which changes the value of one
> of the columns(fields) to "x" and some to "y" and some to "z".
> I would like to save some time by not going through the normal route (after
> selecting the rows, selecting from the drop down menu, the action to be
> performed, then clicking go).
>
> Is it possible to make it faster ?
>
> One of ways i could think is through shortcut keys
>
> Key 1 -> Perform admin action "x" on some rows
>
> Key 2 -> Perform admin action "y" on some rows
>
> key 3 -> Perform admin action "z" on some rows
>
> Will appreciate if you can let me know how to approach this problem ?
>
> Thanks.
>
> Rahul

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



ANN: django-widget-tweaks

2011-01-12 Thread Mikhail Korobov
Hi guys,

Designers often want to add some css classes and html attributes to
django form fields. But now they have to either patch the python code
or copy-paste full html widget output and then customize it. In order
to make them happy I just released an app ( 
https://bitbucket.org/kmike/django-widget-tweaks
) that makes it possible to customize html attributes and css classes
of form fields without touching python code.

Example:

{% load widget_tweaks %}
...
{{ form.city|attr:"autocomplete:off"|add_class:"my_css_class" }}

Hope somebody will find it useful.

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



Re: Query Set involving Model Method

2011-01-16 Thread Mikhail Korobov
It doesn't work that way. ORM translates you queries to SQL and the DB
is responsible for filtering. It is not possible to translate
arbitrary python function to SQL or pass it to DB engine. So you have
to formulate you query using .filter syntax or raw SQL.

Another possibility is to denormalize data: add 'complete' field to
the model and recalculate it on save (or whenever it make sense). This
is often a good solution and it is better than complex queries in
terms of performance.

On 16 янв, 19:16, rmschne  wrote:
> Thanks. I'm still messing with this; but don't think it quite what I'm
> looking for.
>
> I want/need the Model Definition function complete() for use at the
> record level.  I did this as a function since the rules are not based
> simply on the value of the fields.
>
> Ideally, I'd like to have the class DinnerHoseManager(modes.Manager)
> use the complete() function to help return the query set for where
> complete()=True.  How to put that into this class?
>
> It's not the simple filter. Need a little more complexity to
> determining "complete" based on the two if statements.

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



Re: Select x random rows from DB

2011-02-21 Thread Mikhail Korobov
This is the function for getting 1 item that works even if some rows
were deleted that works times faster than order_by('?') even for not-
so-big datasets at least on mysql:

def get_random_item(model, max_id=None):
if max_id is None:
max_id = model.objects.aggregate(Max('id')).values()[0]
min_id = math.ceil(max_id*random.random())
return model.objects.filter(id__gte=min_id)[0]

It assumes that almost all records are still in DB and ids are more or
less successive because otherwise the distribution won't be uniform.
If there are a lot of items in DB then it should be almost safe to
call this several times (and re-call if the same row is obtained).

On 22 фев, 02:10, galago  wrote:
> I need to do this in my tagcloud.

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



Re: Select x random rows from DB

2011-02-21 Thread Mikhail Korobov
Stackoverflow: 
http://stackoverflow.com/questions/962619/how-to-pull-a-random-record-using-djangos-orm/971671#971671

On 22 фев, 03:06, Mikhail Korobov  wrote:
> This is the function for getting 1 item that works even if some rows
> were deleted that works times faster than order_by('?') even for not-
> so-big datasets at least on mysql:
>
> def get_random_item(model, max_id=None):
>     if max_id is None:
>         max_id = model.objects.aggregate(Max('id')).values()[0]
>     min_id = math.ceil(max_id*random.random())
>     return model.objects.filter(id__gte=min_id)[0]
>
> It assumes that almost all records are still in DB and ids are more or
> less successive because otherwise the distribution won't be uniform.
> If there are a lot of items in DB then it should be almost safe to
> call this several times (and re-call if the same row is obtained).
>
> On 22 фев, 02:10, galago  wrote:
>
>
>
>
>
>
>
> > I need to do this in my tagcloud.

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



Re: Unit Testing: temporarily altering django settings

2011-02-21 Thread Mikhail Korobov
Why doesn't setattr work? Just make sure you're setting the proper
option because apps often cache options at e.g. their 'config.py' file
in order to provide default values:

# captha_app/config.py
from django.conf import settings
CAPTCHA = getattr(settings, 'CAPTCHA', True)

So you'll have to change captcha_app.config.CAPTCHA, not the
settings.CAPTCHA in this case.

On 22 фев, 01:47, Cody Django  wrote:
> Thanks -- I didn't know about mock objects, and this is good to know.
> But this doesn't feel like this is the solution I'm looking for.  It's
> a large project, and your proposal would require extensive patching.
>
> Is the solution to create a new testrunner that sets a different
> environment (with different settings) for each app?  Is there another
> way to fool a testcase into thinking that an app has not been
> installed?
>
> Thanks again,
>
> Cody
>
> On Feb 17, 2:00 pm, Phlip  wrote:
>
>
>
>
>
>
>
> > On Feb 17, 12:03 pm, Cody Django  wrote:
>
> > > For example, I have a captcha that is used in parts of a site that
> > > affects form logic.
> > > The django settings has a variable CAPTCHA = True, which acts as a
> > > switch.
>
> > > I'd like to change this setting in the setup for each TestCase.
>
> > You should use a mock object, to fake a-priori things like stochastic
> > user input.
>
> > Python's mock library has a 'patch.object' feature which mocks a
> > method on a class, even before objects of that class are instantiated.
>
> > In most of your setUp calls, patch the captcha handler to trivially
> > pass it, without real user input.
>
> > To test the captcha, mock it to pass or fail.
>
> > --
> >   Phlip
> >  http://c2.com/cgi/wiki?ZeekLand

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