jalanga jalanga - 2 years ago 222
SQL Question

Django query get day from DateTimeField

I have some orders saved in database, I want to retrieve just the day from order, so I did this:


But I get this error:
django.db.utils.OperationalError: (1052, "Column 'date_added' in field list is ambiguous"), and my Order model has the field date_added.

My model:

class Order(models.Model):
user = models.ForeignKey(User, related_name="orders")
date_added = models.DateTimeField(default=timezone.now)

Any solutions?

Answer Source

That error is likely occurring because there is another field named date_added in that SQL: for example, a related table could have the same field.

You could try prepending the table name to the field:


Assuming the table name is app_order.

See more on Django's extra method: https://docs.djangoproject.com/en/1.9/ref/models/querysets/#extra

In particular, look at the section on getting the Blog object count:

SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id

Note the use of the tablename blog_blog.

For more reference:

The value in field list is ambiguous error: Column 'user_id' in field list is ambiguous

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download