So what I need to do is to change few rows in a model DateTime field to 40 days in the past, with Django using a PostgreSQL database. Where I choose all products with an even ID and change the date_uploaded value.
This is what I am currently doing...
from django.core.management.base import BaseCommand
from store.models import Product
import datetime
class Command(BaseCommand):
def handle(self, *args, **options):
all_products = Product.objects.all()
for product in all_products:
if product.pk % 2 == 0:
product.date_uploaded = product.date_uploaded - datetime.timedelta(40,2,0,0)
product.save()
print(product.date_uploaded)
And for some reason when I try to save the product it works with no errors but the DateTime value is not changed. Is there anything wrong with what I am doing?
this is my models.py
class Product(models.Model):
image1 = models.ImageField(upload_to="product_images", default="https://eblossomsl.s3-us-west-2.amazonaws.com/logo.png")
image2 = models.ImageField(upload_to="product_images", blank=True)
image3 = models.ImageField(upload_to="product_images", blank=True)
image4 = models.ImageField(upload_to="product_images", blank=True)
name = models.CharField(max_length=100, unique=True)
category = models.CharField(choices=CATEGORY, max_length=20, default="HRT", db_index=True)
price = models.PositiveIntegerField()
search_query = models.TextField(blank=True, null=True)
date_uploaded = models.DateTimeField(auto_now=timezone.now())
quantity_bought = models.PositiveIntegerField(default=0)
Any help would be greatly appreciated since I am not sure what I am doing wrong.
The problem is in auto_now argument passed into DateTimeField, this argument is responsible for changing the value of the field to the current datetime each time .save() is called on the object, i.e. every time you are running your script it sets it to current datetime and your changes are ignored. What you really need is auto_now_add which sets the value only once at the object creation.
date_uploaded = models.DateTimeField(auto_now_add=timezone.now())
Run makemigrations, apply them and run your script again.
Related
i have tried to look at the django documentation but cant find what i am looking for. I have a django models, and in this model i have defined som logic, the problem is that i cant get the value when i try fetching the recepie through django shell. I want to se if the def recepie_status is working.
My model:
class Recepie(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=60, null=False, blank=True, verbose_name='Recepie name')
description = models.TextField(max_length=500, null=True, blank=True, verbose_name='Description')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# slug = models.SlugField(max_length=255, verbose_name=_('Recepie Slug'), default=name)
share = models.BooleanField(null=True, blank=True)
def recepie_status(self):
import datetime
import date, timedelta, datetime
status=(date.today()-timedelta(days=15))
if self.created_at > status:
return "New"
else:
return "Old"
i have done this in the django shell:
>>> one = Recepie.objects.get(pk=1)
>>> print (one.name) #this works
>>> from datetime import timedelta, date, datetime
>>> print (one.recepie_status())
throws this error in the django shell
E:\Projekt\Fooders\fooders\recepies\models.py in recepie_status(self)
18
19 def recepie_status(self):
20 status=(date.today()-timedelta(days=15))
21 if self.created_at > status:
22 return "New"
ModuleNotFoundError: No module named 'date'
The issue in the following line
import date
import date is cause of the error,
to import date do the following
from datetime import date
Really struggling with this one and could appreciate some help. I have the following model...
class Booking(models.Model):
property = models.ForeignKey(Property, related_name='booking', on_delete=models.SET_NULL, null=True)
check_in_date = models.DateField()
check_out_date = models.DateField()
def __str__(self):
return f"{self.property}"
class Property(models.Model):
name = models.CharField(max_length=100, blank = False)
def __str__(self):
return f"{self.name}"
But when I run the following (below) to retrieve property bookings with a date equal to 2021-05-14, instead of just the bookings with a check_in_date of 2021-05-14 being returned, all the bookings for each property are returned even if they don't have a check_in_date of 2021-05-14
Property.objects.filter(booking__check_in_date='2021-05-14')
Probably something really simple, but I'm new to Django have been stuck on this all morning and could appreciate some help. Thanks
You actually need something like this:
bookings = Booking.objects.filter(check_in_date='2021-05-14')
properties = [booking.property for booking in bookings]
Because property is available on a Booking object and you're initally filtering bookings.
to filter DateFields in Django you must convert the date string to a datetime object:
from datetime import datetime
check_in_date = datetime.strptime('2021-05-14', '%Y-%m-%d')
properties = Property.objects.filter(booking__check_in_date=check_in_date)
I want automatically delete the user object or make default="" in my model after 2 min.
Here is my model. What am I doing wrong!!
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime, timedelta
from django.utils import timezone
from datetime import date
class Action(models.TextChoices):
REQUESTED = 'Requested'
ACCEPTED = 'Accepted'
REJECTED = 'Rejected'
class UserMembership(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255, default='')
student_id = models.CharField(max_length=10, default='')
membership_type = models.CharField(max_length=50)
membership_action = models.CharField(max_length=50, choices=Action.choices, default=Action.REQUESTED)
start_date = models.DateTimeField(default=timezone.now,blank=True,)
#property
def delete_after_thirty_days(self):
time = self.start_date + datetime.timedelta(minutes=2)
if time < datetime.datetime.now():
e = UserMembership.objects.get(user=self.user)
e.delete()
return True
else:
return False
def __str__(self):
return self.name
Basically, after 2 minutes the values of the UserMembership model related to the specific user should be deleted or change back to default values. currently, nothing happens and I don't get any errors as well. Thank you for your time.
I am trying to find the time difference between clock_in and clock_out field. For that i have written logic in save method class Timesheet in models.py. The time differnce between will be stored in clock_duration.
But it gives TypeError
Error - while saving data in model
TypeError at /timesheet/clock-out/
can't subtract offset-naive and offset-aware datetimes
Models.py
from django.db import models
from django.conf import settings
class Timesheet(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="timesheetuser")
clock_in = models.DateTimeField(auto_now_add=True)
clock_out = models.DateTimeField(null=True, blank=True)
clock_date = models.DateTimeField(auto_now_add=True)
clock_duration = models.DateField(blank=True, null=True)
def save(self, *args, **kwargs):
if self.clock_in and self.clock_out:
self.clock_duration = self.clock_out - self.clock_in
super(Timesheet, self).save(*args, **kwargs)
class Meta:
db_table = "timesheet"
It seems stupid but i have hard time since hours and hours about saving my dateTime on db. I'm pretty new in Python and it's not everyday that i'm manipulating datetime.
I have one hour of difference when i'm saving my value. So 18h is now 17h (sorry for my english)
My models is like this:
class Event(models.Model):
title = models.CharField(max_length=245)
description = models.TextField(max_length=750, null=True, blank=True)
start = models.DateTimeField()
end = models.DateTimeField()
created_at = models.DateTimeField(editable=False)
updated_at = models.DateTimeField(editable=False)
slug = AutoSlugField(populate_from='title', unique=True, editable=False)
nb_participant = models.PositiveSmallIntegerField(default=1)
price = models.PositiveSmallIntegerField(default=0)
user = models.ForeignKey(User, editable=False, related_name='author')
address = models.ForeignKey('Address', editable=False, related_name='events')
participants = models.ManyToManyField(User, related_name='participants', blank=True)
class Meta:
db_table = 'event'
def save(self, *args, **kwargs):
if not self.pk:
self.created_at = timezone.localtime(timezone.now())
print self.created_at
self.updated_at = timezone.localtime(timezone.now())
super(Event, self).save(*args, **kwargs)
As you see i have 4 fields with datetime. 2 are actually save automatically save when the model is created.
I resolved the probleme by using timezone.localtime(timezone.now()) instead of timezone.now(). I find that there enter link description here at the bottom of the page. But they said to use timezone.now() in most case. So i don't know why i have this one hour difference.
I have two other fields that are send from my angular frontend to my API( using django rest framework)
I put a screenshot. The first object i send by angular.As you seen the date is well formatted.
The second object is the response from my API and i have lost one hour (so the GMT +1)
Why ? I'm totally block so if someone has a solution, i'll be very happy :)
My settings.py:
LANGUAGE_CODE = 'fr-fr'
TIME_ZONE = 'Europe/Paris'
USE_L10N = True
USE_TZ = True
Thanks.
In settings file try with USE_TZ=False, and use normal datetime.now().