Update a queryset in django - python

I need to update the data on the database once I get all the values of that data with current DateTime..i.e
My Model:
class Load_Balancing(models.Model):
instance_name = models.CharField(max_length=100)
instance_visit = models.DateTimeField(null=True)
sequence = models.IntegerField()
I want to get the value with the last sequence number inserted in the database and update its time to the current time.
I tried:
instances = Load_Balancing.objects.all().order_by("-sequence")[:1]
a = Load_Balancing.objects.filter(sequence=instances.sequence).update(instance_visit= datetime.datetime.now())
But it's not working.

If you want to update the latest one, you can do that with:
from django.utils import timezone
instance = Load_Balancing.objects.all().latest('sequence')
instance.instance_visit = timezone.now()
instance.save()

Related

How to update a field of Django Model Object whenever that particular object is fetched as a part of QuerySet from Database

I have a field called pending_since for a Ticket model. This contains the the difference between the date when the ticket is created ( created_on field ) and the current date.
Now, when a single ticket is fetched, then I am able to update this field as below.
views.py
def pending_days_calculator(date1):
current_date = timezone.now()
diff = current_date - date1
diff_in_days = diff.total_seconds() / ( 60*60*24)
pending_days = round(diff_in_days,2)
return pending_days
#login_required(login_url=settings.CUSTOM_LOGIN_URL)
def ticket_detail(request, ticket_no):
ticket = Ticket.objects.get(ticket_no=ticket_no)
ticket.pending_since = pending_days_calculator(ticket.created_on)
ticket.save()
if request.method == 'POST':
.....other logic here.....
But, when a bunch of Ticket objects are fetched at a time as shown below, is there any way to update this field for each object, other than looping through the queryset.
#login_required(login_url=settings.CUSTOM_LOGIN_URL)
def common_pool(request):
tickets = request.user.ticket_set.exclude(ticket_status='closed').order_by('sla')
Ticket model has ForeignKey reference to user model GHDUser
models.py for reference
class Ticket(models.Model):
ticket_no = models.CharField(max_length=10, blank=True)
raised_by_user = models.ForeignKey(GHDUser, on_delete=models.CASCADE,related_name='raised_ticket', default=1)
created_on = models.DateTimeField(default=timezone.now)
pending_since = models.FloatField(default=0.0)
If you want to calculate pending_since for each object of Django Model, you can use a property method for it
#property
def pending_since(self):
return pending_days_calculator(self.created_on)
This would do the job. You can also move the logic in pending_days_calculator in side the property.

Why choices CharField default value also defines DateField default value

# models.py
class Url(models.Model):
STATUS_CHOIX = [
('ATTENTE', 'ATTENTE'),
('VALIDE', 'VALIDE'),
('ERREUR', 'ERREUR'),
]
URL = models.URLField(max_length=500)
STATUS = models.CharField(max_length=10, choices=STATUS_CHOIX, default='ATTENTE',)
DATE = models.DateField(auto_now_add=True)
CIBLE = models.CharField(max_length=15)
Here is my model, when I try to save a Url object, I got this strange behaviour, DATE field gets STATUS's default value which is 'ATTENTE' instead of having the record creation date.
I have tried to swap auto_now_add=True with default=date.today() but I get the same problem.
Here is a print screen of what I have in database when I run the following code:
from scrapper.models import Url
a = Url(URL="some_url", CIBLE="some-target")
a.save()

Django ORM Issue

I am learning RestAPI and When I try to post data to update my database columns the modified_on column should automatically populated to current date and time but it is not updating.
I am currently using django cassandra engine ORM where there is no functionality like auto_add_now() or auto_now().
Can any one give a suggestion where am I going wrong?
Model Class:
class Mydb(DjangoCassandraModel):
id = columns.UUID(primary_key=True, default=uuid.uuid4())
user_name = columns.Text()
user_email = columns.Text(default=None)
user_password = columns.Text()
description = columns.Text()
creation_date = columns.DateTime(default=datetime.datetime.today(), static=True)
modified_on = columns.DateTime(default=datetime.datetime.today())
My Serialization class:
class TaskSerializer(serializers.Serializer):
# id = serializers.UUIDField(default=uuid.uuid4)
USER_ID = serializers.UUIDField(default= uuid.uuid4(),source='id')
# user_name = serializers.CharField(max_length=50)
USER_NAME_FIELD = serializers.CharField(max_length=50, source='user_name')
USER_EMAIL = serializers.CharField(source='user_email')
USER_PASSWORD = serializers.CharField(max_length=20, source='user_password')
EXPLANATION = serializers.CharField(max_length=100, source='description')
MODIFIED_AT = serializers.DateTimeField(default=datetime.datetime.today(), source='modified_on')
CREATED_ON = serializers.DateTimeField(default=datetime.datetime.today(), source='creation_date')
def create(self, validated_data):
return Mydb.objects.create(**validated_data)
def update(self, instance, validated_data):
# instance.id = validated_data.get('id', instance.id)
instance.user_name = validated_data.get('user_name', instance.user_name)
instance.user_email = validated_data.get('user_email', instance.user_email)
instance.user_password = validated_data.get('user_password', instance.user_password)
instance.description = validated_data.get('description',instance.description)
instance.modified_on = validated_data.get('modified_on', instance.modified_on)
instance.save()
# instance.creation_date = validated_data.get('creation_date', instance.creation_date)
You should rather use utils now for timezone aware times
from django.utils.timezone import now
also in model you should set function not evaluated value ( no parenthesis after now )
MODIFIED_AT = serializers.DateTimeField(default=now, source='modified_on')
MODIFIED_AT = serializers.DateTimeField(default=datetime.datetime.today(), source='modified_on')
to
MODIFIED_ON = serializers.DateField(default=datetime.datetime.today(), source='modified_on')
change MODIFIED_AT to MODIFIED_ON
You can try:
create_date = models.DateField(auto_now_add=True,
verbose_name=u'Create date')
update_date = models.DateTime(auto_now=True,
verbose_name=u'Update date')
auto_now_add automatically set the field to now when the object is first created.
auto_now=True automatically set the field to now every time the object is saved.
Doc is here.
Please make sure to add the auto_now=True for your modified_at filed, in your model.
It automatically sets the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.
Example:
class Mydb(DjangoCassandraModel):
creation_date = columns.DateTime(auto_now_add=True)
modified_on = columns.DateTime(auto_now=True)
Docs Here:
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.DateField.auto_now
You use default=datetime.datetime.today() as your default value for the fields. Since you call the function immediately (by adding ()), the function is called exactly once on the first load of the code and the datetime at that moment is put into the default value and not updated until you reload the code (a.k.a. restart the server).
If you want to always use the then current time, leave away the () to cause Django to call the function each time. default=datetime.datetime.today
It's preferable for you to use now though, like iklinac did in his answer, as that also respects your timezone settings. His anwer also leaves out the parenteses, yielding the correct result.
from django.utils.timezone import now
...
MODIFIED_AT = serializers.DateTimeField(default=now, source='modified_on')

How to fetch last 24 hours records from database

I have Orders model which stores orders of users. I'd like to filter only orders which has been issued (order_started field) on the last 24 hours for a user. I am trying to update following view:
def userorders(request):
Orders = Orders.objects.using('db1').filter(order_owner=request.user).extra(select={'order_ended_is_null': 'order_ended IS NULL',},)
Order model has following fields:
order_uid = models.TextField(primary_key=True)
order_owner = models.TextField()
order_started = models.DateTimeField()
order_ended = models.DateTimeField(blank=True, null=True)
How can I add the extra filter?
You can do it as below, where you add another argument in the filter call (assuming the rest of your function was working):
import datetime
def userorders(request):
time_24_hours_ago = datetime.datetime.now() - datetime.timedelta(days=1)
orders = Orders.objects.using('db1').filter(
order_owner=request.user,
order_started__gte=time_24_hours_ago
).extra(select={'order_ended_is_null': 'order_ended IS NULL',},)
Note that Orders is not a good choice for a variable name, since it refers to another class in the project and begins with caps (generally used for classes), so I've used orders instead (different case).

Django UpdateView wont delete tha old entry if primary key is edited

So lets say we have this model:
class Student(models.Model):
am = models.SmallIntegerField(unique=True, primary_key=True) # XXX: max_value = 10000
date_enrolled = models.DateField('Date Enrolled')
semester = models.IntegerField(default=1)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
undergraduate = models.BooleanField(default=True)
An update view like this:
class StudentUpdateView(SqlPresenterMixin, StudentMixin, UpdateView):
model = Student
form_class = StudentForm
template_name = "profapp/student_form.html"
slug_field = "am"
Then this test fails:
class TestStudent(TestCase):
def setUp(self):
self.c = Client()
Student.objects.create(am=2222, first_name="Chris",
last_name="Perivolas",
date_enrolled=datetime.date(year=2010, day=15,
month=2))
Student.objects.create(am=7362, first_name="Mary",
last_name="Karagewrgena",
date_enrolled=datetime.date(year=2010, day=15,
month=2))
def test_update(self):
"""
"""
r = self.c.post("/profapp/students/2222/update/",
dict(am=7363, first_name="Chris",
last_name="Perivolas",
date_enrolled="3/15/2010",
semester=2,
undergraduate=1))
self.assertEquals(Student.objects.filter(am=2222).exists(), False)
In short update view doesn't delete the old entry when updating a primary key. What is the best way of solving this?
According to Django documentation, PK should never change. PK is what ties your object to a specific row in the DB. When you change the PK, Django loses the connection to the original row in the DB and assumes that you want to create another row.
You should add another field to act as changeable id if you really need it.

Categories