Hi one of my Django models has a the following field
created_at = models.DateTimeField(blank=True,null=True)
However when I check the data type it shows as String
print(self.created_at)
print(type(self.created_at))
2018-01-10T20:53:19Z
<class 'str'>
Funny thing is the same code running on my production server shows it as
2016-04-21 09:38:38+00:00
<class 'datetime.datetime'>
I am using python3 and Django 1.10.6.
Any idea what is causing this ?
Databases don't store Python data types, so the django ORM does some transforming and casting for you to return you an equivalent Python type.
For example, DateField fields use a Python datetime object to store
data. Databases don’t store datetime objects, so the field value must
be converted into an ISO-compliant date string for insertion into the
database.
(From the documentation on the save() method)
This only works if there is already data to be read from that particular field.
In other words, if you are creating a new record, the value will be a string because there is no existing value to the field.
If the object is being updated, then the value will be an date time object if you haven't updated that field.
Django uses the same save() method for creating new records and updating existing records.
Related
I have a table name service_table which have some fields. A field have days name like Sunday, Monday, Tuesday etc.. I want to change all the column value in postgres database table into lower case.
For Instance
'Sunday' update as 'sunday'
I am written a query
update service_table set days=lower(days);
but it shows
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Note: This table has some foreign key.
You can do this in Django shell
from django.db.models import F
from django.db.models.functions import Lower
service_table.objects.update(days=Lower(F('days'))
Django update() is a bulk operation for direct updates.
Django F() makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory.
F() helps to pull the model field value, then it process to the requirement and use update() to save it back
I'm reading django doc and see how django knows to do the update or insert method when calling save(). The doc says:
If the object’s primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE.
If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT link.
But in practice, when I create a new instance of a Model and set its "id" property to a value that already exist in my database records. For example: I have a Model class named "User" and have a propery named "name".Just like below:
class User(model.Model):
name=model.CharField(max_length=100)
Then I create a new User and save it:
user = User(name="xxx")
user.save()
now in my database table, a record like id=1, name="xxx" exists.
Then I create a new User and just set the propery id=1:
newuser = User(id=1)
newuser.save()
not like the doc says.when I had this down.I checked out two records in my database table.One is id = 1 ,another is id=2
So, can anyone explain this to me? I'm confused.Thanks!
Because in newer version of django ( 1.5 > ), django does not check whether the id is in the database or not. So this could depend on the database. If the database report that this is duplicate, then it will update and if the database does not report it then it will insert. Check the doc -
In Django 1.5 and earlier, Django did a SELECT when the primary key
attribute was set. If the SELECT found a row, then Django did an
UPDATE, otherwise it did an INSERT. The old algorithm results in one
more query in the UPDATE case. There are some rare cases where the
database doesn’t report that a row was updated even if the database
contains a row for the object’s primary key value. An example is the
PostgreSQL ON UPDATE trigger which returns NULL. In such cases it is
possible to revert to the old algorithm by setting the select_on_save
option to True.
https://docs.djangoproject.com/en/1.8/ref/models/instances/#how-django-knows-to-update-vs-insert
But if you want this behavior, set select_on_save option to True.
You might wanna try force_update if that is required -
https://docs.djangoproject.com/en/1.8/ref/models/instances/#forcing-an-insert-or-update
I am writing a weblog application in django. As part of this, I have a view function that fetches an object from the database corresponding to a single blog post. The field that I am using to query the database is the published date (pub_date) which is of type DateTime (Python). I have a MySQL database and the type of the column for this field is datetime. But I am not able to fetch the object from the database though I am passing the correct date attributes. I am getting a 404 error.The following is my view function:
def entry_detail(request,year,month,day,slug):
import datetime,time
date_stamp = time.strptime(year+month+day,"%Y%b%d")
pub_date = datetime.date(*date_stamp[:3])
entry = get_object_or_404(Entry,pub_date__year=pub_date.year,pub_date__month=pub_date.month,pub_date__day=pub_date.day,slug=slug)
return render_to_response('coltrane/entry_detail.html',{'entry':entry})
The following is the URL of the individual post that I want to fetch:
http://127.0.0.1:8000/weblog/2014/oct/28/third-post/
And this is how the pub_date column value for the third-post in the database looks like:
2014-10-28 13:26:39
The following is the URL pattern:
url(r'^weblog/(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$','coltrane.views.entry_detail'),
You're doing some odd things here: you're converting to a time, then converting that to a datetime.date, then extracting the year, month and day as integers and passing them to the query. You could bypass almost the whole process: the only thing you need is to convert the month, the other parameters can be passed directly:
month_no = datetime.datetime.strptime(month, '%b').month
entry = get_object_or_404(Entry, pub_date__year=year, pub_date__month=month_no, pub_date__day=day, slug=slug)
I have a 2 models with a foreign/Primary key to same model.
model Foo:
FK(Too, pk)
model Coo:
FK(Too, pk)
model Too:
blah = charfield()
In the views I am seeing some very strange behavior. I think I am doing something very wrong.
I want to replicate a object of Too and then save it. For e.g.
too = Too.create(blah="Awesome")
too.save()
foo = Foo.create(too=too)
foo.save()
too.id = None #Copy the original
too.save()
coo = Coo.create(too=too)
coo.save()
print foo.too.id
print coo.too.id
#above 2 print statements give same id
When I check in the admin the both foo and coo have different too object saved. But while printing it is showing the same. Why is that happening. I think I am doing something fundamentally wrong.
Django looks at the primary key to determine uniqueness, so work with that directly:
too.pk = None
too.save()
Setting the primary key to None will cause Django to perform an INSERT, saving a new instance of the model, rather than an UPDATE to the existing instance.
Source: https://stackoverflow.com/a/4736172/1533388
UPDATE: err, using pk and id are interchangeable in this case, so you'll get the same result. My first answer didn't address your question.
The discrepancy here is between what is occurring in python vs. what can be reconstituted from the database.
Your code causes Django to save two unique objects to the database, but you're only working with one python Too instance. When foo.save() occurs, the database entry for 'foo' is created with a reference to the DB entry for the first Too object. When coo.save() occurs, the database entry for 'coo' is created, pointing to the second, unique Too object that was stored via:
too.id = None #Copy the original
too.save()
However, in python, both coo and foo refer to the same object, named 'too', via their respective '.too' attributes. In python, there is only one 'Too' instance. So when you update too.id, you're updating one object, referred to by both coo and foo.
Only when the models are reconstituted from the database (as the admin view does in order to display them) are unique instances created for each foreign key; this is why the admin view shows two unique saved instances.
I select date using DateField and insert date value using this.
form = DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
and then, I want to show selected value using DateField(form) in HTML from database
(when create profileForm())
Birth: selectbox(------), selectbox(------), selectbox(------)
: solved
(if edit profile page using profileForm())
Birth: selectbox(1987) selectbox(10) selectbox(25)
-> I want it
How to insert value into DataField, and show selectDateWidget?
Your problem is not too clear.
You should post more information from you forms.py and your views.py. Are you using forms.Form or forms.ModelForm?
Either way I think your question is about using initial data in your form.
Note that this field in particular accepts a python datetime object (see: http://docs.python.org/2/library/datetime.html).
https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
Use is like this:
f = ContactForm(initial={'my_date_field': datetime.datetime.now()})
If you are using ModelForm is is like this:
f = ContactForm(instance=Contact.objects.get(pk=1))
This will initialise all the values from the models (and thus database).