I want to know if there is any way to change Django dateTimeField format, I want to set the time using auto_now_add attribute but I can't get it to save it with the format I want. I know that there is a way suing models.DateField but I need to use auto_now_add. Thanks
I don't know if it would help any one in the future but here's the answer :
I had to change the field in my model to created = models.DateField(blank=False, auto_now_add=True) and create a new field in the serializer class like this (on top of the Meta class) created = serializers.DateTimeField(read_only=True), that worked quite fine.
Related
Is there a way to order result of a model queryset by update time of its instances? i.e. the instance that has been saved most recently comes first and so on.
You will need to add a timestamp field to your model. For example in my own code I add a date_updated field for this very purpose.
Your custom models don't have this by default so you have to add it.
last_edit = models.DateTimeField(auto_now_add=True)
You will have to update this in the save method (or another method) of your model.
import datetime
self.last_edit = datetime.datetime.now()
If you have a field on your model that tracks this update time (more information on this here), then yes, you can just use that in a normal ordering specification.
If you don't track updates on your model, no, that is not possible.
having used cakephp in the past, one thing (perhaps the only thing?) i liked about it was that it had a "create" and "update" timestamp capability that was lovely - simply put, when you first added an item, the "create" date was set (assuming you named it right - create_date, i think)
Anytime thereafter, if an update was performed, the "update" field was set to the current time.
Does django have this as well? If so, what/how do i name the fields to get it to pick them up?
It is not added to your model built-in in every table. You must add it as field to your model.
class Message(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Message in this case your table's name.
Sure it has!
Check auto_now and auto_now_add in the doc
I would like to have a model in Django that has multiple pictures associated with it. I'm evaluating possible options.
One picture for one model is easily done with the models.ImageField(...).
However, I would like a array (or set) of pictures. It can be just paths, not necessarily ImageField objects.
The problem is, how do I create that field in a Django model? I am assuming I will need to create a field that is not part of models.WhateverField. Is that possible? Can I define a non-model field, such as:
class MyModel:
name = models.CharField(max_length=10)
picture_list = []
and then do:
def sample_add_picture_view(request):
picture = "sample.jpg"
model = MyModel.objects.get(id=sample_id)
model.picture_list.append(picture)
model.save()
return HttpResponseRedirect('index.html')
Could this be done? If not, what could be a better solution? Thank you !
You need to create two separate models and link them with a ForeignKey field, like so:
class Item(models.Model):
name = models.CharField(max_length=255)
class ItemImage(models.Model):
image = models.ImageField(upload_to="item_images")
item = models.ForeignKey('Item', related_name="images")
It is possible to make a custom field to store multiple items, but it's a really bad idea. You would have to serialise an array into the database, making maintenance very difficult. Using a separate model means you can store extra information such as upload times, image captions etc with little extra effort.
I am gradually replacing a legacy database front end with a django based system. All models are Managed = False, to preserve the original db structure.
However I have struck a problem where a field in a table is computed. The field is defined in (pseudo) sql as full_name = fname|| ||lname.
I can define the full_name field as a charfield; and I can read it no problems, however any attempt to update the record results in an update error on that field.
I can use a #property; but that replicates the functionality in django, rather than displaying the results from the db itself. Using this approach will cause problems with more complex fields (in tables I am yet to get to) that are defined with UDFs.
What is really needed is a 'read_only' or 'computed' attribute on the model itself; what is the best way to achieve this?
Do you just want to define a method in your class? Something like:
def Person(models.Model):
fname=models.CharField(...)
lname=models.CharField(...)
def fullname(self):
return self.fname+" "+self.lname
(not exactly sure what Managed=False means...)
if you are trying to make calculation on a database models and pass the value of a model field to another model field of the same class model, using a defined function then this solution might help you. for example lets assume you have an investment company and you give 20% per month for the capital each user invested, you would want want to pass value from capital model to a function that calculates the percentage interest, and then you will pass that function into another field monthly_payment and get saved in the database.
1) pip install django-computed-property
2) add 'computed_property' to your installed apps in project settings.
3) in your models.py, import computed_property then
class Investment(models.Model):
name = models.CharField(max_length=200)
capital = models.FloatField(null=False)
percentage = models.CharField(max_length=5)
duration = models.CharField(max_length=10, default="1 months")
monthly_payment = computed_property.ComputedFloatField( compute_from='monthly_percentage', null=False, blank=False)
then your function to perform the calculation will go thus
#property
def monthly_percentage(self):
return (20 / 100) * self.capital
Note: what i discovered was if you use the inbuilt django fields be it FloatFiled or IntegerField, this function won't read the amount you are passing in to get your 20% calculations.i hope this works for you as i stated all as they worked for me,cheers.
I have a model (and model form based on it) that has several time fields. I want these fields to be optional such that the user may leave some empty. My problem is that I continue to receive "Column 'mechreturn_tm' cannot be null" errors when I attempt to save an instance where one or more of these fields are blank. I've used the following approaches:
mechreturn_tm = models.TimeField(blank=True, null=False)
mechreturn_tm = models.TimeField(blank=True, null=True)
mechreturn_tm = models.TimeField()
none seem to work. what am I doing wrong?
Are you sure you still get the error using the second approach (both blank and null set to to True)?
Keep in mind that you'll need to recreate the DB table when you make this change since syncdb won't alter an existing table. That may be why you got the error even with the correct code.
Setting blank=True on a model field means that the field is allowed to be blank when validating a form with that field.
Setting null=True means that the model can be saved to the DB without any value at all for that field.
http://docs.djangoproject.com/en/dev/topics/db/models/#field-options