django-orm

How can one get the set of all classes with reverse relationships for a model in Django?

Given: from django.db import models class Food(models.Model): """Food, by name.""" name = models.CharField(max_length=25) class Cat(models.Model): """A cat eats one type of food""" food = models.ForeignKey(Food) class Cow(models.Model): """A cow eats one type of food""" food = models.ForeignKey(Food) cl...

Django - Custom virtual model field with companion stored field

I would like to have a ConfirmationField field type. I want this field to work like a boolean field. I don't need to store this information on database instead I would like to store the date of confirmation on a seperate field. class MyModel(models.Model): confirmation = ConfirmationField() m = MyModel() m.confirmation # False m.c...

Django ORM: Get most recent prior object that meets a certain condition

Hi there, Given an object like: class M(models.Model): test = models.BooleanField() created_date = models.DateTimeField(auto_now_add=True) Given sample data (assume monotonically increasing automatic created_date): M(test=False).save() M(test=True).save() M(test=False).save() X = M(test=True).save() M(test=False).save() Y =...

Django: Perform case-insensitive lookups by default

I need to perform case-insensitive queries on username by default when using the Django Auth framework. I tried fixing the issue by writing a custom subclass of Queryset and overriding the _filter_or_exclude method and then using that subclass in a custom manager for the User model- from django.db.models import Manager from django.db.m...

How do I use the the Django ORM to query this many-to-many example?

I have the following models: class Author(models.Model): author_name = models.CharField() class Book(models.Model): book_name = models.CharField() class AuthorBook(models.Model): author_id = models.ForeignKeyField(Author) book_id = models.ForeignKeyField(Book) With that being said, I'm trying to emulate this query using the ...

Help with deleting reconds in Django

for u in Users.objects.all(): for g in u.group.all(): if g not in Groups.objects.filter(domain__user=u.id): u.group.filter(id=g.id).delete() How do I delete the entries in relationship table. In this case I have a many to many relationship between Groups and Users. The delete statement in the above code delete...

Django ORM: caching and manipulating ForeignKey objects

Consider the following skeleton of a models.py for a space conquest game: class Fleet(models.Model): game = models.ForeignKey(Game, related_name='planet_set') owner = models.ForeignKey(User, related_name='planet_set', null=True, blank=True) home = models.ForeignKey(Planet, related_name='departing_fleet_set') dest = model...

how to use filter in django

hi, class Status(models.Model): someid = models.IntegerField() value = models.IntegerField() status_msg = models.CharField(max_length = 2000) so my database look like: 20 1234567890 'some mdg' 20 4597434534 'some msg2' 20 3453945934 'sdfgsdf' 10 4503485344 'ddfgg' so I have to fetch values contain a givin...

Django ORM Query to limit for the specific key instance.

Projectfundingdetail has a foreign key to project. The following query gives me the list of all projects that have any projectfundingdetail under 1000. How do I limit it to latest projectfundingdetail only. projects_list.filter(projectfundingdetail__budget__lte=1000).distinct() I have defined the following function, def latest_fundi...

fetching single child row based on a max value using Django ORM

I have a model, "Market" that has a one-to-many relation to another model, "Contract": class Market(models.Model): name = ... ... class Contract(models.Model): name= ... market = models.ForeignKey(Market, ...) current_price = ... I'd like to fetch Market objects along with the contract with the maximum price of ea...

django - reorder queryset after slicing it

I fetch the latest 5 rows from a Foo model which is ordered by a datetime field. qs = Foo.objects.all()[:5] In the following step, I want to reorder the queryset by some other criteria (actually, by the same datetime field in the opposite direction). But reordering after a slice is not permitted. reverse() undoes the first ordering, g...

Why do I get an error when I try to execute a query with parameters in postgreSQL?

The db is PostgreSQL. When I try to execute a query with parameters, such as this one cursor.execute(""" SELECT u.username, up.description, ts_rank_cd(to_tsvector(coalesce(username,'')|| coalesce(description,'')) , to_tsquery('%s')) as rank FROM auth_user u INNER JOIN pm_core_userprofile up on u.id = up.user_id ...

fetching row numbers in a database-independent way - django

Let's say that I have a 'Scores' table with fields 'User','ScoreA', 'ScoreB', 'ScoreC'. In a leaderboard view I fetch and order a queryset by any one of these score fields that the visitor selects. The template paginates the queryset. The table is updated by a job on regular periods (a django command triggered by cron). I want to add a...

django orm, how to view (or log) the executed query?

Hi folks, Is there a way I can print the query the Django ORM is generating? Say I execute the following statement: Model.objects.filter(name='test') How do I get to see the generated SQL query? Thanks in advance! ...

Django ORM Creates Phantom Alias in SQL Join

Hello, I am executing the following code (names changed to protect the innocent, so the model structure might seem weird): memberships = models.Membership.objects.filter( degree__gt=0.0, group=request.user.get_profile().group ) exclude_count = memberships.filter( member__officerships__profile=req...

Same Table Django ORM Soft Delete Method Okay?

Hello, I'm using the following setup to implement soft deletes in Django. I'm not very familiar with Django under the hood so I'd appreciate any feedback on gotchas I might encounter. I'm particular uncomfortable subclassing a QuerySet. The basic idea is that the first call to delete on a MyModel changes MyModel's date_deleted to t...

Django RelatedManager's .create() usage?

I have two models: Play and PlayParticipant, defined (in part) as: class PlayParticipant(models.Model): player = models.ForeignKey('Player') play = models.ForeignKey('Play') note = models.CharField(max_length=100, blank=True) A piece of my code has a play p which has id 8581, and I'd like to add participants to it. I'm try...

Django: is there a way to count SQL queries from an unit test?

I am trying to find out the number of queries executed by a utility function. I have written a unit test for this function and the function is working well. What I would like to do is track the number of SQL queries executed by the function so that I can see if there is any improvement after some refactoring. def do_something_in_the_dat...

Default image for ImageField in Django's ORM

I'm using an ImageField to store profile pictures on my model. How do I set it to return a default image if no image is defined? ...

query for values based on date w/ Django ORM

I have a bunch of objects that have a value and a date field: obj1 = Obj(date='2009-8-20', value=10) obj2 = Obj(date='2009-8-21', value=15) obj3 = Obj(date='2009-8-23', value=8) I want this returned: [10, 15, 0, 8] or better yet, an aggregate of the total up to that point: [10, 25, 25, 33] I would be best to get this data direc...