Re: Getting hold of an instance of a model from inside RelatedManager

2011-01-25 Thread Euan Goddard
can't you do self.model.main?

On Jan 25, 3:34 pm, kmpm  wrote:
> I have some issues with getting hold of the instance of a Model to which a
> RelatedManager got contributed to.
> Is that at all possible and if so, how?
>
> From *my_method* below I can get hold of the model *RelatedStuff* by calling
> self.model but that really doesn't get me there.
>
> class MainStuff(models.Model):
>     
>
> class RelatedStuff(models.Model):
>     ...
>     main = models.ForeignKey(MainStuff)
>     objects = CustomManager()
>
> class CustomManager(models.Manager):
>     use_for_related_fields=True
>
>     def my_method(self):
>         #here I would like to access the instance of MainStuff to which this
> got contributed

-- 
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: Announcing djeneralize

2011-01-25 Thread Euan Goddard
Hi Tom,

I hadn't seen that. django_polymorphic looks pretty fully featured and
from a quick look, I'd say it accomplishes everything we set out to
do. I guess a use case for djeneralize would be to handle the simple
specializations and generalizations and nothing more. The impetuous to
write the package was just to augment Django's model inheritance which
did almost everything we needed.

Thanks again for the link.

Euan

On Jan 25, 2:26 pm, Tom Evans  wrote:
> On Tue, Jan 25, 2011 at 11:43 AM, Euan Goddard  wrote:
> > Hi,
>
> > I've recently been working on an open source project to augment the
> > inheritance of models in Django. This project, called "djeneralize"
> > allows you to declare specializations on your models and then query
> > the general case model and get back the specialized instances. A
> > simple example of the models might be:
>
> Hi Euan, sounds good.
>
> Had you come across django_polymorphic[1]? This library also covers
> similar goals.
>
> Cheers
>
> Tom
>
> [1]http://bserve.webhop.org/django_polymorphic/

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



Announcing djeneralize

2011-01-25 Thread Euan Goddard
Hi,

I've recently been working on an open source project to augment the
inheritance of models in Django. This project, called "djeneralize"
allows you to declare specializations on your models and then query
the general case model and get back the specialized instances. A
simple example of the models might be:

class Fruit(BaseGeneralizedModel):
name = models.CharField(max_length=30)

def __unicode__(self):
return self.name

class Apple(Fruit):
radius = models.IntegerField()

class Meta:
specialization = 'apple'

class Banana(Fruit):
curvature = models.DecimalField(max_digits=3, decimal_places=2)

class Meta:
specialization = 'banana'

class Clementine(Fruit):
pips = models.BooleanField(default=True)

class Meta:
specialization = 'clementine'

which then allows the following queries to be executed:

>>> Fruit.objects.all() # what we've got at the moment
[, , ]
>>> Fruit.specializations.all() # the new stuff!
[, , ]

I hope this type of general case/specialization might be of some use
to someone else out there. We're planning on integrating this work in
a large project we're undertaking on content categorization.

Grab the source at github: https://github.com/2degrees/djeneralize

or you can easy_install it (easy_install djeneralize).

Feedback, etc. very welcome.

Thanks, Euan

-- 
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: method of method

2011-01-25 Thread Euan Goddard
I agree with the previous poster - the title is misleading as the word
"method" is incorrect in both places.

It seems that the original poster is talking about denormalizing data.
However, this is unnecessary as the ORM allows for this type of data
to be retrieved any how, e.g.
Car.objects.all().select_related(depth=1) will allow statements like:
car.producer.country_of_origin

If you want access to country_of_origin directly on the Car instances,
I'd suggest a property:

@property
def country_of_origin(self):
   return self.producer.country_of_origin

Euan

On Jan 25, 11:30 am, bruno desthuilliers
 wrote:
> On 25 jan, 11:57, Jaroslav Dobrek  wrote:
>
> > Hi,
>
> > can I use methods of methods in Django?
>
> What's a "methods of methods" ???
>
> > Like so:
>
> > class Car(models.Model):
> >     producer = models.ForeignKey(CarProducer)
> >     country_of_origin = producer.country_of_origin
>
> What is CarProducer.country_of_origin ? A method ? A model.Field ?
> Something else ?
>
> > This doesn't seem to work.
>
> What happens ? And what did you expect to happen ?

-- 
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: Reconnecting after a database restart

2011-01-10 Thread Euan Goddard
As far as I know Django maintains a persistent connection to the
database server and restarting the server without restarting the
client isn't possible. We never restart our live database server in
production (we fail over to a secondary server so that the app is
essentially only vulnerable for a few seconds whilst the failover
happens and a subsequent app restart). I think the only thing you can
do is to restart the app as soon as you've restarted the DB server.

All that said, it may be possible to get Django to reconnect, but from
reading the source in the DB layer, I don't recall seeing anything
like that.

On Jan 10, 3:25 pm, Brennan Sellner  wrote:
> Hi folks,
>
> We're using the Django database layer as part of a Twisted application
> [1], and we're having some problems with Django failing to reconnect to
> the database after the database server restarts.  It works great
> otherwise, but once the database server restarts, the Django database
> layer throws exceptions on every database touch.  Is there any way to
> configure Django (or psycopg2) to automatically reconnect?
>
> The traceback we're seeing is below [2].  The problem is reliably
> reproducible by restarting Postgres, then triggering an action in our
> Twisted application that touches the database.  It persists until we
> restart the application.
>
> Versions:
>   Django 1.2.1
>   Psycopg2 2.0.13
>   Postgresql 8.4.5
>   Ubuntu 10.04
>
> Thanks,
>
> -Brennan
>
> [1] We're planning on adding a real Django app in the near future, and
> wanted to maintain the same database abstraction throughout the system.
>
> [2] Traceback:
>
> File "/usr/lib/pymodules/python2.6/gjeter/executive/Executive.py", line
> 164, in robotPair
>    p.save()
>  File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line 435, in 
> save
>    self.save_base(using=using, force_insert=force_insert, 
> force_update=force_update)
>  File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line 528, in 
> save_base
>    result = manager._insert(values, return_id=update_pk, using=using)
>  File "/usr/lib/pymodules/python2.6/django/db/models/manager.py", line 195, 
> in _insert
>    return insert_query(self.model, values, **kwargs)
>  File "/usr/lib/pymodules/python2.6/django/db/models/query.py", line 1479, in 
> insert_query
>    return query.get_compiler(using=using).execute_sql(return_id)
>  File "/usr/lib/pymodules/python2.6/django/db/models/sql/compiler.py", line 
> 783, in execute_sql
>    cursor = super(SQLInsertCompiler, self).execute_sql(None)
>  File "/usr/lib/pymodules/python2.6/django/db/models/sql/compiler.py", line 
> 727, in execute_sql
>    cursor.execute(sql, params)
>  File "/usr/lib/pymodules/python2.6/django/db/backends/util.py", line 15, in 
> execute
>    return self.cursor.execute(sql, params)
>  File 
> "/usr/lib/pymodules/python2.6/django/db/backends/postgresql_psycopg2/base.py",
>  line 44, in execute
>    return self.cursor.execute(query, args)
> django.db.utils.DatabaseError: server closed the connection unexpectedly
> This probably means the server terminated abnormally
> before or while processing the request.

-- 
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: Multiple AJAX sends within a views.py-function

2010-06-11 Thread Euan Goddard
If you're worried about the data getting out of order use a counter in
JS and always ensure that you only update the page when you get the
correct (i.e. current) counter back.

I think what you're talking about isn't possible in normal HTTP. I
think you have a one request, one response situation.

Euan

On Jun 11, 4:15 pm, Christoph  wrote:
> Hi,
>
> normally in views.py I have a function that takes a request and
> returns a render_to_response or the like. I, however, would like it to
> take a request and have Django reply with multiple responses. Is there
> a way to do this, or is this not possible with HTTP anyway?
>
> What I am trying to achieve: Have a a view that gets called and in it
> I have a JS/AJAX script that asks for some data. However, calculating
> the data takes a while and it comes one after the other. So I thought
> that I could send the data as soon as it becomes available.
>
> In my example I have a graph (using flot) and it would also look
> natural to have the data points show up one by one.
>
> A different approach: Have JS ask for more data (using GET) until the
> view responses sets a flag (NO_MORE_DATA = True). I don't like this,
> since for me this looks like it defies the A in AJAX and the view
> would lose all parameters (I.e. which points it already sent and which
> not). However, I don't know much JS, nor AJAX nor do I understand the
> HTTP protocol good enough.
>
> Maybe this has been done before? Is there a way of having server-side
> generated AJAX-actions? Is there a way of having Django send something
> within a views-function (as opposed to returning it at the end)?
>
> Some possible code:
>
> def my_view(request):
>     data =
> MyModel.objects.filter('something').order_by('somethingelse')
>     for item in list(data): # Note, I don't do this but this is just
> to show how what I want
>         send_json(do_something(item)) # send_json() is the crucial
> (non-existing) function that I am looking for
>     return None # or maybe return Done or something like it
>
> Best regards,
> Christoph

-- 
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: ordering integers with regroup

2010-06-11 Thread Euan Goddard
It should be easy enough to write your own tag providing you're
expecting your input in the form . I've written
a bit of code that should do this:

import re

LABEL_RE = re.compile(r'^(\w+) (\d+)$')

def order_by_number(unordered_data):
tokenized_data = []
for item in unordered_data:
# tokenize this item:
match = LABEL_RE.match(item)

if match is None:
print "No pattern match found for %s" % item
continue

tokenized_item = (match.group(1), int(match.group(2)))
tokenized_data.append(tokenized_item)

# Now sort by the numbered tokens:
tokenized_data.sort(key=lambda i: i[1])

# Finally return the detokenized data:
return ['%s %d' % t for t in tokenized_data]

if __name__ == "__main__":
unordered_data = [
"District 1",
"District 10",
"District 14",
"District 2",
"District 20",
"District 29",
"District 3",
"District 30",
]

print order_by_number(unordered_data)

You should be able to put this into a filter pretty easily.

Euan

On Jun 9, 4:34 pm, Nick  wrote:
> You are right, I wasn't even thinking about it like that. This is bad
> news as the information is coming across as "District 45" from another
> source and so I don't have just a district number to go off of. State
> government data is always terrible to work with.
>
> On Jun 9, 10:04 am, Scott Gould  wrote:
>
> > If you're ordering on "District 1", "District 2", etc. then the number
> > is part of a string and will be sorted alphabetically. I image your
> > only recourse will be to use the numeric field directly, and deal with
> > prepending "District " to it in some other fashion.
>
> > On Jun 9, 10:38 am, Nick  wrote:
>
> > > Has anyone come across an ordering issue with the regroup tag whereby
> > > if the field that is being ordered is an integer you get the following
> > > problem:
>
> > > say you have the grouped field "District" and the following groupings
>
> > > District 1
> > > District 2
> > > District 3
> > > District 10
> > > District 14
> > > District 20
> > > District 29
> > > District 30
>
> > > Their ordering will come out:
>
> > > District 1
> > > District 10
> > > District 14
> > > District 2
> > > District 20
> > > District 29
> > > District 3
> > > District 30
>
> > > I can see why this is happening, but how do I tell the regroup tag to
> > > sort as though 1 were 01, etc. Adding a 0 to the front isn't really an
> > > option as their are thousands of records that reach from 1 - 250
>
> > > Thanks in advance.

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



Re: Using array type data in Django/ Postgresql

2010-06-11 Thread Euan Goddard
I'd just create a related model and use a many-to-many field.

Alternatively you could write your own field, but this would restrict
your application to postgres only.

Euan

On Jun 10, 1:03 pm, bjja  wrote:
> Hi
>
> Psycopg2 supports array types but I can not find any evident
> information whether Django supports them.
>
> Bjørn

-- 
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: Running syncdb from an install script in django_project/install

2010-06-11 Thread Euan Goddard
This sounds like a path type issue and these sorts of things are a
PITA to sort out. Have you tried setting the settings path a bit more
explitly:

os.environ["DJANGO_SETTINGS_MODULE"]="django_project.settings"

I had some trouble with kind of thing in a project I was working on
(https://launchpad.net/django-audit/). I wrote a test suite which
needed a fake Django app to test a load of things and I had to use the
full path to the settings file:

os.environ['DJANGO_SETTINGS_MODULE'] =
"tests.fixtures.sampledjango.settings"

Are you installing the application using setuptools? If not and you
can't put it in the site-packages, I'd consider using a virtualenv.

Euan

On Jun 11, 2:11 pm, Stodge  wrote:
> I'm writing an install script that resides in django_project/install
> and one of things it does, is programmatically run syncdb. My current
> code for this is correct if I do:
>
> cd ..
> python
> import os
> os.environ["DJANGO_SETTINGS_MODULE"]="settings"
> from django.core.management import call_command
> call_command('syncdb', interactive=False)
>
> If I copy this code into my installer, or indeed do the same as above,
> but inside the django_project/install directory it fails:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.6/site-packages/django/core/management/
> __init__.py", line 166, in call_command
>     return klass.execute(*args, **defaults)
>   File "/usr/lib/python2.6/site-packages/django/core/management/
> base.py", line 221, in execute
>     self.validate()
>   File "/usr/lib/python2.6/site-packages/django/core/management/
> base.py", line 249, in validate
>     num_errors = get_validation_errors(s, app)
>   File "/usr/lib/python2.6/site-packages/django/core/management/
> validation.py", line 28, in get_validation_errors
>     for (app_name, error) in get_app_errors().items():
>   File "/usr/lib/python2.6/site-packages/django/db/models/loading.py",
> line 145, in get_app_errors
>     self._populate()
>   File "/usr/lib/python2.6/site-packages/django/db/models/loading.py",
> line 60, in _populate
>     self.load_app(app_name, True)
>   File "/usr/lib/python2.6/site-packages/django/db/models/loading.py",
> line 82, in load_app
>     if not module_has_submodule(app_module, 'models'):
>   File "/usr/lib/python2.6/site-packages/django/utils/
> module_loading.py", line 14, in module_has_submodule
>     for entry in package.__path__:  # No __path__, then not a package.
> AttributeError: 'module' object has no attribute '__path__'
>
> I've tried adding the project's path to sys.path, but that doesn't
> make a difference. Is there a way to do this from a sub-directory?
> 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: Get last object with certain value

2010-06-11 Thread Euan Goddard
Hi,

I've done something similar to this using annotation. It is a bad
nasty, but should work.

Firstly annotate all the MyModel instances with the max value of the
pk of the MyOtherModel:

qs = MyModel.objects.annotate(last_pk=Max('myothermodel__pk'))

Then filter these based on the myString:

qs = qs.filter(myothermodel__myString=certainStringValue)

Now get a values list of the last_pks:

pks = qs.values_list('last_pk', flat=True)

Finally select all myOtherModel instances based on these pks:

other_models = myOtherModel.object.filter(pk__in=last_pks).

This will only do one SQL query.

This should be fine until you've got loads of potential hits, where
the sub-select will be a beast, although Postgres is certainly OK
accepting lists of 1000s of pks to filter on.

As an aside you might want to consider following the python style
guide (http://www.python.org/dev/peps/pep-0008/) to make your code a
bit more readable.

Euan


I think what you want is:

MyModel.objects.filter

On Jun 11, 1:27 pm, Odd  wrote:
> I have these two rather simple models that looks something like this:
>
> class MyModel(models.Model):
>       myName=models.CharField(max_length=60)
>
> class MyOtherModel(models.Model):
>        myString=models.CharField(max_length=60)
>        myModel=models.ForeignKey(MyModel)
>
> I will eventually have quite a number of MyOtherModelinstances. I have
> made a form where the users enters a string and a myModel instance,
> and it gets saved to the database. I need a query to get all the
> MyModel instances that has a certain stringvalue in myOtherModel, but
> only if it is the last entered one. My current solution is this:
>
> for i in mymodel.myothermodel_set.all():
>
> myOtherModel=MyOtherModel.objects.filter(myModel=i).order_by('-id')[:
> 1].get()
>          if myOtherModel.myString==certainStringValue:
>                objectsToRetur.append(i)
>
> This works, but I think it's not a very good. Is there maybe a better
> solution?
>
> Thanks!
>
> Odd-R.

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



Re: django python pi-charts/graphs

2010-06-02 Thread Euan Goddard
I would recommend using google charts. There are a couple of python
implementations for this. I've used GChartWrapper with some success,
but found it a little clunky in its implementation.

Euan

On Jun 2, 7:35 am, rahul jain  wrote:
> Hi Django,
>
> I would like to represent my db/model content in the form of
> pi-charts/graphs. Is there any django python module that already
> exists ?
>
> --RJ

-- 
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: Having to rstrip the " [] " from the end of your Key when posted?

2010-05-29 Thread Euan Goddard
Yeah jQuery added this annoying "feature" in 1.4.

There's no "nice" way around it other than to recognise that any JS
arrays will have this suffix.

Euan

On 29 May, 05:33, pyfreak  wrote:
> I accept this as normal now. I think, what I'll need to do if I'm
> against stripping off the two characters, is simply putting the value
> that serves as the key, directly into the array as the last element.
> Simple enough.
>
>   So in views function:
>      It'll look like:   request.POST["imthekeyval[]"] = ("someval",
> "anotherval", "imthekeyval")
>
>    code:
>
>      for key in request.POST.getlist(key):
>          py_array = request.POST.getlist(key)
>
>       (  py_array has all I need, no need to use the key which is
> sporting the mutant "[]" growth at the end  )
>
> On May 28, 5:41 pm, pyfreak  wrote:
>
>
>
> > I'm having to, in Javascript, create a dictionary ( my_dict = {} ),
> > then put in some Arrays.
>
> >  my_dict["stringkey"] = Array("hey","hey1")
> >  my_dict["stringkey1"] = Array("more","stuff")
>
> > In the views function:
>
> >     for key in request.POST:
> >              prop_rec = request.POST.getlist(key)
>
> >  The Python var, "prop_rec"  has the array contents that I'm
> > expecting.
>
> >  However, I also need to use "key".  But when I'm sending over stuff
> > from javascript like above,
> > the key has a "[]" tacked on the end of it, like "stringkey[]"
>
> > If I code the normal in js:
> >   my_dict["stringkey"] = "1",
> >         then  if I do a print key in the views function, I don't get
> > the brackets at the end
>
> > So just wondering if that's normal.

-- 
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: Get pk before commit

2010-05-29 Thread Euan Goddard
Hi,

Could you explain the situation in a little more detail as I don't
quite follow what you mean. As far as I'm aware if you have something
like the following:

>>> my_inst = MyModel(foo="bar", ...)
>>> my_inst.save()

You'll have the pk at this point even if the transaction hasn't been
committed (providing you haven't specified a custom primary key
field). So you should be able to do:

>>> my_pk = my_inst.pk

and use this for the other field that you need to set. If the other
field is a foreign key to my_inst, then you should just be able to do:

>>> other_model_inst.related_object = my_inst
>>> other_model_inst.save()

I'm not sure how this is affected by transactions. Unless you have a
really good reason to, I'd let Django handle the transaction
management for you, then you don't need to worry about save points,
committing and rolling back.

Euan

On 29 May, 07:56, TheIvIaxx  wrote:
> Hello, I am trying to figure out how to get a pk in the middle of a
> transaction. I need to set a field in the model based on the
> ID(default pk) to be given.  As far as a i know, this ID should be
> allocated during the transaction.  So i would imagine it would do the
> INSERT, then i could get the pk and do what i need to do, then proceed
> with the commit.
>
> Is this possible?
>
> 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: best approach to solve statistical problem

2010-05-28 Thread Euan Goddard
Darren,

This seems like quite a complex problem and I'm not sure whether the
Django ORM would be up to it. I've had a lot of trouble when using
multiple annotations on Querysets when JOINs are involved as Django
does the wrong thing.

Have you considered using a schemaless DB like MongoDB for your data
storage rather than a relational model? Your data does look quite
relational though, but you might find some of the map/reduce
functionality good.

Euan

On May 28, 5:50 am, darren  wrote:
> Needing to get this done, I went with SQL.  The sql seems rather
> inefficient.  But, my data set will be rather small.  I posted what I
> went with on Pastebin:  http://pastebin.com/VmiYNXan(good for 24
> hrs).
>
> I don't have much data loaded (just one tournament).  But, you can see
> the resulting table of data here: rankintornadoes.com.
>
> I would still like to know if this would be the recommended Django
> way.  Any advice would be welcome.
>
> Darren
>
> On Thu, May 27, 2010 at 2:19 PM, darren  wrote:
> > I'm looking for ideas on the best way to approach this problem.
> > Should I write raw SQL, stay with the ORM or even mix Javascript with
> > either ORM or SQL?
>
> > I want to keep up with player stats for a baseball team.  I've been
> > reading up on aggregates and annotations.  And, I'm getting somewhere
> > with it.  But, not quite all the way yet.  I  also wrote some SQL that
> > accomplishes most everything I need all at once.  I think I could run
> > with it, too.
>
> > To calculate things like "on base percentage" or "batting average", I
> > need to mix math both vertically and horizontally in the table.  One
> > way I thought about handling this is to build an HTML table of data
> > using a queryset based on this example in the Django documentation:
>
> > Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
>
> > except, I would need something that summed 3 or 4 different columns.
>
> > At that point, I could use javascript to Sum() the total of each and
> > calculate averages.  So, a table would be built like:
>
> >          A            B              C                D            E
> >                                 F
> >             G                                     H
> > Player Name |  Hits  |  Strike Outs  |  Walks  |  Fouled Out |
> > Javascript Calcuated Total at Bats |  Javascript Calc. Batting AVG  |
> > Javasctipt On Base %
> > Player 1             3              2                5             2
> >                         A+B+C+D+E
> >  B/F                              (B+D)/F
> > Player 2             4              2                5             1
> >                         A+B+C+D+E
> >  B/F                              (B+D)/F
>
> > My models contain 3 tables that join people, tournaments and an "at
> > bat".  The "AtBat" class is where the statistical data will be
> > recorded. The model looks like this.  So, I'm saving one result per
> > record:
>
> > 101  class AtBat(models.Model):
> > 102     atbat_id = models.AutoField(primary_key=True)
> > 103     player = models.ForeignKey(Person, to_field='f_name',
> > verbose_name='Player', limit_choices_to={'relationship' : 'Player' })
> > 104     game = models.ForeignKey(Score, to_field='scores_id',
> > verbose_name='Game')
> > 105     result = models.CharField('Result', choices=(('H', 'Hit'),
> > ('BB', 'Walk'), ('K', 'Strike Out'), ('FO', 'Ground or Fly Out'),
> > ('Sacrifice', 'Sacrafice')), max_length=10)
>
> > One of my goals would be to allow users to select certain players,
> > date ranges or games to filter the results. I'm not sure how that
> > might impact the solution.
>
> > Any suggestions?

-- 
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: Annotating a queryset without aggregation

2010-05-28 Thread Euan Goddard
Hi Tom,

Whilst Django annotation is great, it is rather simplistic in nature
and can only do very basic Count, Sum, Avg, etc. which do not allow
any filtering (i.e. a WHERE clause in the SQL).

Unless there are major differences in 1.2 (which I haven't seen) then
you won't be able to do what you want I'm afraid.

Euan

On May 28, 10:26 am, Tom Evans  wrote:
> Hi all
>
> I want to annotate a qs with a computed field from one of its current
> fields, and then filter on the annotated field. I cannot work out how
> I'm supposed to do this in the ORM (or even if I can).
>
> Basically, I have a model with a username field, that in this case
> contains an email address. I want to extract the domain of that email
> address, and then filter the queryset based upon the value of the
> domain.
>
> So, in code:
>
> domains = UsageLogEntry.objects \
>   .filter(action=ACTION_FAILED_REGISTRATION,
> sub_action=SUB_ACTION_DOMAIN_DISALLOWED) \
>   .annotate(domain=...) \
>   .exclude(domain='').values_list('domain', flat=True)
>
> Im clueless about what to put in annotate().
>
> In 1.0.x, I used a horrific hack with extra(), that has stopped
> working with 1.2:
>
>   domains = UsageLogEntry.objects \
>       .filter(action=ACTION_FAILED_REGISTRATION,
>                sub_action=SUB_ACTION_DOMAIN_DISALLOWED) \
>       .extra(
>           select={ 'domain': 'SUBSTRING(username, LOCATE("@", username)+1)' },
>           # XXX hacks ahoy - this makes the where clause look like
>           #    WHERE ... AND 1 HAVING `domain` != ''
>           where=[ "1 HAVING `domain` != ''", ],
>          ) \
>       .order_by('domain') \
>       .values_list('domain', flat=True)
>
> This is because (I think) in 1.0.x, the where clause was bare, and in
> 1.2 it is enclosed by braces, which makes my hacky insertion of a
> having clause illegal syntax.
>
> Thanks for any pointers
>
> Tom

-- 
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 avoid "in" query for large sets?

2010-05-24 Thread Euan Goddard
I've found the best way to solve these problems is to use a
values_list queryset and inject the result of the into the outer
query. Django is smart and doesn't actually evaluate the values_list
query and instead injects that as a sub query in the SQL.

However in this case can't you simply do:

User.objects.filter(quiz__score__gt=90). ?

I guess it depends on what sort of relationship you have between user
and quiz, but if quiz has a foreign key of user (which your snippet
implies), then this should work.

Euan


On May 24, 3:23 pm, omat  wrote:
> ops, this doesn't work, because the the Quiz model is pointing to the
> User model, and i want to filter on the quiz model and get the
> matching User instances. but in the example in the docs, the query is
> on the parent model.
>
> quiz_qs = Quiz.objects.filter(score__gt=90)
> User.objects.filter(quiz__in=quiz_qs)
>
> is not possible as User does not have a quiz attribute.
>
> and daniel, yours, saying "user.id in Quiz queryset" does not look ok:
> User.objects.filter(id__in=Quiz.objects.filter(score__gt=90))
>
> Still stuck. Any ideas?
>
> --
> oMat
>
> On May 24, 4:58 pm, omat  wrote:
>
>
>
> > @cliff: you are right, but i am writing an extension to an existing
> > app. i want to use the models as-is if possible.
>
> > i found the part in the docs:
>
> > inner_qs = Blog.objects.filter(name__contains='Cheddar')
> > entries = Entry.objects.filter(blog__in=inner_qs)
>
> > thanks.
>
> > On May 24, 4:22 pm, Tomasz Zieliński
>
> >  wrote:
> > > On 24 Maj, 08:58, Daniel Roseman  wrote:
>
> > > > User.objects.filter(id__in=Quiz.objects.filter(score__gt=90))
>
> > > Nice thing, is it documented somewhere (I think I haven't this
> > > before) ?
>
> > > --
> > > Tomasz Zielinskihttp://pyconsultant.eu
>
> > > --
> > > You received this message because you are subscribed to the Google Groups 
> > > "Django users" group.
> > > To post to this group, send email to django-us...@googlegroups.com.
> > > To unsubscribe from this group, send email to 
> > > django-users+unsubscr...@googlegroups.com.
> > > For more options, visit this group 
> > > athttp://groups.google.com/group/django-users?hl=en.
>
> > --
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group 
> athttp://groups.google.com/group/django-users?hl=en.

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



Re: where can I find good unit test examples?

2010-05-06 Thread Euan Goddard
Hi Chris,

First of all, I never had much luck writing reproducible tests for
Django models with the fixture system that comes built into Django as
I never got consistent results and found the XML a pain to maintain. I
came across Fixture - http://code.google.com/p/fixture/ We have this
running with our Django installation for all our unittests and it
works a treat. There are some examples of unittests in the source for
that.

I've used that in an open source project called Django audit to test
some model related bits and pieces, but I wouldn't necessarily attest
to their being "good tests" as it's a work in progress. Have a look at
https://launchpad.net/django-audit/ in the tests section.

For good unittesting in general in a Django type manner (but not
specifically model related) have a look at 
http://pypi.python.org/pypi/twod.wsgi/

Hope this helps, Euan

On May 6, 9:23 am, Chris Withers  wrote:
> Hi All,
>
> Where can I find good examples of django unit tests?
>
> I currently just want to test my models and some helper functions, but
> they will do a .save() on a bunch of model instances.
>
> Any help gratefully recieved!
>
> Chris
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group 
> athttp://groups.google.com/group/django-users?hl=en.

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



Re: django_audit 0.0.2

2010-05-05 Thread Euan Goddard
On May 4, 11:21 am, Dj Gilcrease  wrote:
> Google code wont let me change the project name without deleting and
> recreating the project so I just added a note to the top

That is quite annoying. I hope you can find a good solution to that
problem.

> "This is a fairly comprehensive Audit Trail App for use with standard
> RDBMS databases. If you are looking for a solution for NoSQL there is
> a great project by the same name but differing author 
> @https://launchpad.net/django-auditthat uses MongoDB."

That is very kind of you and I take your point about MongoDB
availability. We are having to adjust our architecture quite
significantly to allow the inclusion of this technology. Annoyingly
the Debian packages for MongoDB aren't fixed, so there is some messing
around with APT to get it to work properly.

> and a little NoSQL vs SQL comparison of the two solutions

I think that's a fair comparison. With Django 1.2 offering multiple
databases, it will be good to be able to potentially store auditing
information in other SQL databases as to no pollute the application
data directly if you care about that sort of thing.

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



Re: django_audit 0.0.2

2010-05-04 Thread Euan Goddard
On May 1, 4:00 am, Dj Gilcrease  wrote:
> Ya I saw the announcement on it the day I pushed my code to google,
> hence my remark about not being tied to a "NoSQL" solution. I had
> already created the project name by the time I saw the announcement so
> just went with it

This is all very well, but should either of these projects get to pypi
there's going to be some serious trouble. Since I'm the main author of
the "noSQL" django-audit, please let me know how you want to proceed.
I'm already using the project in some pre-production code so would
rather not rename my project. If you could rename yours that would be
really helpful as this clearly a case of two people simultaneously
coming up with the same name.

Thanks, Euan

-- 
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: Track "before" and "after" state of an object when editing in the Admin?

2010-04-28 Thread Euan Goddard
Hi Derek,

> How and where can this be done?

I've recently been developing a project that uses MongoDB to audit
Django models. I've just published an early version of this work on
launchpad: https://launchpad.net/django-audit/ I haven't got around to
writing any documentation yet, but if you're keen to get hold of
something that can do audit your models, take a look at the tests and
the source and see what you can do.

Good luck, Euan

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