FAQ Database Discussion Community


Django 1.6 + MySQL : Type Cast MySQL variable to search for Max, Avg

mysql,django,django-orm,django-aggregation
My Model is sort of like class ServiceUtilization(models.Model): device_name = models.CharField() service_name = models.CharField() data_source = models.CharField() current_value = models.CharField() sys_timestamp = models.IntegerField() Now, here current_value represents the value in Float stored as VarChar, w.r.t the time stored as unixtime While trying to get Max and Average values of current_value...

Django 1.8 conditional annotation results in INNER JOIN instead of LEFT OUTER JOIN

django,django-models,django-queryset,django-orm,django-1.8
The models: class Bar(GenericModel): ... class Foo(GenericModel): bar = models.ForeignKey(Bar, related_name='foo_bar') The query: bars = Bar.objects .prefetch_related('foo_bar') .annotate(sum_foo=Sum( Case( When(foo_bar__is_deleted=False, then='foo_bar__amount'), default=Value(0), output_field=IntegerField() ) ) ) The former results in an inner join: SELECT ... FROM "bar" INNER JOIN "foo" ON ( "bar"."id" = "foo"."bar_id" ) ... What I intend...

How do I filter this in Django ORM

python,sql,django,django-orm
Here is my models.py class Category(models.Model): name = models.CharField(max_length=200, default='') slug = models.SlugField(max_length=100,default='',unique=True) def __unicode__(self): return self.name class SubCategory(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=200, default='') slug = models.SlugField(max_length=100,default='',unique=True) class TutorInfo(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=255, default='') category =...

Why does adding a JOIN completely modify the query planner behaviour?

postgresql,django-orm,postgresql-9.3,query-planner
I have two queries: SELECT "recipes_recipe"."short_name", COUNT(DISTINCT "recipes_recipe"."quantity_type") AS "quantity_type_count", SUM("measures_measure"."standard") AS "volume", CASE WHEN COUNT(DISTINCT "recipes_recipe"."quantity_type") = 1 THEN (SUM((T7."standard" * T8."standard")) / SUM(T8."standard")) ELSE NULL END AS "weighted_temperature" FROM "orders_orderitemresult" INNER JOIN "orders_orderitem" ON ( "orders_orderitemresult"."order_line_id" = "orders_orderitem"."id" ) INNER JOIN "orders_order" ON ( "orders_orderitem"."order_id" =...

Django Bulk Update to Trigger save()

python,django,django-orm
I need to re-save all my models Users.objects.all().update(active=True) In the model: def save(self, *args, **kwargs): self.url = "XYZ" super(User, self).save(*args, **kwargs) However, the above does not trigger the save() method on these model. So no url = XYZ is set. Is this possible? Update: Looks like I cannot do this...

Django loads parent object when it's not required

django,django-orm
Here is my simplified models configuration: class Topic(Sortable): course = SortableForeignKey(Course) publish = models.BooleanField(default=False) title = models.CharField(max_length=200) text = models.TextField() estimated_time = models.PositiveIntegerField(null=True, blank=True)) class Task(models.Model): topic = models.ForeignKey(Topic) class Quiz(Task): questions = models.TextField() def __unicode__(self): return u'[#%s] %s: %s' % (self.id, self.topic.title, capitalize(_("quiz"))) As you can see, there is...

Is it possible/sensible to customize Django's auto-through tables to include other fields…through-factory?

python,django,django-orm
I know that django will helpfully generate a through table for simple many-to-many tables. However if you want to add information about the relationship, you need a 'linker' or through table. This example from the docs gives an example: from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self):...

How to get reverse relationship values as a list

django,django-models,django-orm
assume i have some models like this. class Employee(models.Model): FullName = models.CharField(max_lenth = 100) class Projects(models.Model): EmployeeFK = models.ForeignKey(Employee) ProjectName = models.CharField(max_length = 100) class Departments(models.Model): EmployeeFK = models.ForeignKey(Employee) DateJoined = models.DateField() i want to get my output like this. [ {"id" : 1 , "FullName" : "John Doe 1"...

Django Oracle Database - Varchar2 Vs NVarchar2

django,django-models,oracle10g,django-orm,django-oracle
I have the following character field in my model (against Oracle Database). trans_status = models.CharField(max_length=10, blank=True, null=True) Why does Django create this field as NVARCHAR2 instead of VARCHAR2? I mean, Why trans_status NVARCHAR2(10) NULL, instead of trans_status VARCHAR2(10) NULL, What is the difference? How does Django decide on one and...

Algoritm to sort object by attribute value without allowing gaps or duplicates

python,sql,django,sorting,django-orm
I have a agenda with multiple dates, each date can contain 0 > ... items. Items can be sorted by position, positions should be Integer values without gaps and duplicates. class Item(models.Model): date = models.DateField() position = models.IntegerField() def move_to(position): qs = self.__class__.objects.filter(date=self.date) # if the position is taken, move...

Django query with annotated conditional expression uses INNER JOIN. How do I get it to use OUTER JOIN?

django,django-queryset,django-orm,django-1.8
I have a "Meal" model with a foreign key to "Food". Each meal has a rating: good, bad, or indifferent. I want to query a list of all foods and annotate the count of each type of meal rating, but some foods have no meals yet, so I want the...

Using Django-genereted SQL tables in another project

python,sql,django,django-models,django-orm
There is a Django-powered site. There is a need to create a stand-alone service (written in another language & platform) which should be able to perform all the CRUD operations on the SQL database that's used by the Django site. Obviously, new tables won't be available to the Django site...

Django: bigger querysets & small no. of database hits or vice versa

mysql,django,django-queryset,django-orm
I am developing a website on django & MySQL which is similar to linkedin in terms of complexity and functionality and am expecting steep growth for a few months. I have one question. While designing the models and the views, I have two options. Either go for smaller number of...

Django 1.8 ArrayField append & extend

python,django,postgresql,django-orm,django-1.8
Django 1.8 will come with new advanced field types including ArrayField these rely on PostgreSQL and are implemented at a DB level. PostgreSQL's array field implements an append method. However I can't find any documentation on appending an item to an ArrayField. This would clearly be very useful as it...

how to get group name using User in django

django,django-authentication,django-orm
I am stuck in django's group module can any one tell me how to solve it. my problem is now i'm dispalying the username of the logged-in user, i want to display group-name and the profiles present in that group along with the username.and my views are like this, def...

Django ORM Left Join With GROUP BY and SUM

python,django,django-orm,django-1.8
I am using Django 1.8. I have a User model and a UserAction model. A user has a type. UserAction has a time, which indicates how long the action took. They look like this: class User(models.Model): user_type = models.IntegerField() class UserAction: user = models.ForeignKey(User) time = models.IntegerField() Now what I...

django - get list of objects by filtering a list of objects

django,django-models,django-views,django-orm
I am creating a user activity streams. models for activity: class Activity(models.Model): actor = models.ForeignKey(User) action = models.CharField(max_length=100) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') pub_date = models.DateTimeField(auto_now_add=True, auto_now=False) model for Relationship: class Person(models.Model): user = models.OneToOneField(User) relationships = models.ManyToManyField('self',...

Determine if an attribute is a `DeferredAttribute` in django

python,django,django-models,django-orm,django-cache-machine
The Context I have located a rather critical bug in Django Cache Machine that causes it's invalidation logic to lose its mind after a upgrading from Django 1.4 to 1.7. The bug is localized to invocations of only() on models that extend cache machine's CachingMixin. It results in deep recursions...

Using .filter to show DB entries created (today) in Django

python,django,django-orm
My form allows users to create entries into the database and is timestamped with: created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) This creates entries like: 2015-02-20 03:10:00 How can I use the .filter to search just the day part of the timestamp? I have so far: for running in viewteam.daily_risk_set.all().filter(team =...

filter/limit django order_by

django,django-orm
Using the django ORM, Is there a way to limit or filter the scope of what order_by applies to? Product.objects.filter( product_type__name=choices.PRODUCT_BOOK ).order_by( # need to order these last names by those # who have a role code of "A01", then "B01" 'contributor__writer__last_name' ) ...

Django GenericIPAddress field is not validating input

python,django,validation,django-models,django-orm
Hi I have the following Django model class AccessPointIPAddress(models.Model): '''Model for storing AccessPoint IP Addresses.''' ap = models.ForeignKey(AccessPoint, related_name='ip_addresses') ip_address = models.GenericIPAddressField(protocol='IPv4') datetime = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['datetime'] get_latest_by = 'datetime' And I am assuming that django's GenericIPAddressField does some string validation that a string is indeed a...

Use different model's field with the same value in Django

python,django,orm,django-orm
I have two Django models, and I want to have same-value field in both of them. Basically, when CarModification.engine_status is 'inactive' or 'active', I want to have the same field in Car set to the latest CarModification's field value. class CarManager(models.Manager): def get_queryset(self): # Select engine_status from the latest #...

Django ORM: All items not in table

django,django-models,django-orm
I've got two models: class SchedulerEvent(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) class SchedulerEventReceipt(models.Model): event = models.ForeignKey(SchedulerEvent, unique=True) generated_on = models.DateTimeField() paid_on = models.DateTimeField() I'm trying to figure out how to get a list of all SchedulerEvents that aren't in the SchedulerEventReceipt table for a particular...

Custom column names in Intermediary table for many-to-many model in Django

django,django-models,django-orm
Below is the code block of a Many-To-Many relationship between two models. Having searched and researched there appears to be no elegant way to create custom id column names for the foreign keys in the intermediary (or link) table that Django creates. The custom name using db_table='pizza_link_topping' creates the desired...

Get the raw query from executemany(sql, params) django/postgresql

django,postgresql,django-orm
How do I get the raw query from cursor.executemany(sql, params) ? I'm running a query that doesn't work, and I would like to see the query after it's been formated by the cursor. Thanks....

Annotate a column field from relation on django

django,python-2.7,django-orm
I got two models defined Owner and Dog class Dog(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(Owner) adopted_date = models.DateTimeField() class Owner(models.Model): name = models.CharField(max_length=255) I want to make a list with all the owners with the amount of dogs adopted by date. Example: OwnerName Date Amount Richard 15/11/24 2 Jow...

Django Querysets - Using .annotate() after .extra()

django,django-queryset,django-orm
Let us say I have a very simple model like this one: class Test(models.Model): category = models.CharField(unique=True) start_time = models.DateTimeField() end_time = models.DateTimeField() Basically, I want to use Django's ORM API to get the average duration per category. The SQL query will look something like this: SELECT category, AVG(end_time -...

Django Many-To-One relationship filter set

python,django,django-orm
I have a couple models setup like so: Group(models.Model): name = models.TextField(max_length=255) Thing(models.Model): location = models.TextField(max_length=255) group = models.ForeignKey(Group) That's just an example to illustrate the relationship, so forgive any syntax errors. My question is, how can find a group which has a particular set of locations? I should be...

Django getting especific object using QuerySet in reverse relationship many-to-one

python,django,django-queryset,django-orm,many-to-one
Lets say I have the following models: Chat(models.Model): community = models.ForeignKey(Community, related_name="chats", null=True, blank=True) .... Community(models.Model): slug = models.CharField(max_length=250, unique=True, default='') .... Profile(models.Model): public_name = models.CharField(max_length=20, unique=True) community_subscriptions = models.ManyToManyField('Community', through='CommunitySubscription') chat_subscriptions = models.ManyToManyField('Chat', through='ChatSubscription') .......

How to query all the elements with this condition in the query?

python,django,django-models,django-orm
For the sake of simplicity, let's say I have the following models: class Tag(models.Model): name = models.CharField(max_length=255) class Supplier(models.Model): name = models.CharField(max_length=90) tags = models.ManyToMany(Tag, null=True, blank=True) I have a list of liked suppliers and I would like to have all the tags this suppliers have. How can I get...

Bug in Django CacheMachine ignores saving of Model?

python,django,django-orm,django-cache-machine
I have a very simple Django class: from django.db import models class MyClass(models.Model): a = models.IntegerField() b = models.IntegerField() def __str__(self): return "MyClass #%s: a: %s, b %s" % (self.pk, self.a, self.b) This class works fine when I perform CRUD-type operations: >>> from statistics.models import MyClass >>> print MyClass.objects.all() []...