Django Model Default Datetime with Timezone Always Midnight - django

Current field in my model is as follows...
from django.utils import timezone
class Test(models.Model):
assigned_date_time = models.DateTimeField(
null=True, verbose_name='Assigned Date', default=timezone.now)
When this object is created, the assigned_date_time is always 0 or rather "midnight" of today. I'm not quite sure what I am doing wrong.
Thank you in advance.

In order for the field default to be executed, a value should not be assigned to that field.

Related

Django query to filter only first objects with particular field names

model
class UserAction(models.Model):
ACTION_CHOICES = (
("LogIn", "Entered"),
("LogOut", "Gone Out"),
("Away", "Away from Computer"),
("Busy", "Busy"),
("DoNotDisturb", "Do not disturb"),
("Online", "Online and Available"),
)
action_name = models.CharField(choices=ACTION_CHOICES, default="LogIn")
user = models.ForeignKey(Profile, related_name="actions")
action_time = models.DateTimeField(default=timezone.now(), editable=False)
class Profile(models.Model):
name = models.CharField(max_length=120)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now())
I need to query UserAction, in such a way that I want only the last UserAction of each user. My solutions were too much time consuming. That's why looking for an optimised answer.
You can annotate the Profiles with a Subquery expression [Django-doc]:
from django.db.models import OuterRef, Subquery
Profile.objects.annotate(
last_action=Subquery(
UserAction.objects.filter(
user_id=OuterRef('pk')
).order_by('-action_time').values('action_name')[:1]
)
)
The Profiles in the queryset will have an extra attribute .last_action with the action_name of the last related UserAction.
Note: Django's DateTimeField [Django-doc]
has a auto_now_add=… parameter [Django-doc]
to work with timestamps. This will automatically assign the current datetime
when creating the object, and mark it as non-editable (editable=False), such
that it does not appear in ModelForms by default.

How to bypass WSGI error in django filter

from django.db import models
from django.contrib.auth.models import User
class Transfer(models.Model):
id = models.AutoField(primary_key=True)
amount = models.DecimalField(max_digits=10, decimal_places=2)
name=models.CharField(max_length=55)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
Is it possible to make a request like this without WSGI error?
result = Transfer.objects.filter(name=request.name)
filter()
filter(**kwargs)
Returns a new QuerySet containing objects that match the given lookup parameters.
The lookup parameters (**kwargs) should be in the format described in Field lookups below.
Where charfield == String object, so try to str(request.name)

Django migration issue for boolean field

I have models and there was no Boolean field in the very beginning when i run makemigraiton and migrate
In that mean time, i added some post...
later i added new field called is_printable as boolean field...
this is my current models:
from django.db import models
import datetime
from django.utils import timezone
Create your models here.
class Article(models.Model):
title = models.CharField(max_length=50)
body = models.TextField()
category = models.CharField(
null=False,
blank=False,
max_length=50,
)
is_printable = models.BooleanField()
date = models.DateTimeField(timezone.now)
when i add
is_printable = models.BooleanField()
I cant run migrate command, it throws me an error called
django.core.exceptions.ValidationError: ["'2019-07-07 06:56:52.693378+00:00' value must be either True or False."]
What is possible solution for this?
When you added is_printable field and ran makemigrations Django would've asked you to enter default value for the newly added field, what is the default value you gave? I presume you gave timezone.now() and because of that it would've thrown error during migrate.

How can I define the date format in models in django?

I'm defining a date variable inside my model AccessRecord using DateField attribute and I've tried every possible thing to define it. But every time a new error arises. Sometimes it says "Date is not defined" sometimes "Date should be in YYYY-MM-DD format" during migration.
Can someone give me a permanent solution for this? I'm using django 2.1.7.
I've tried default='' and default=blank and quite of few others
from django.db import models
from datetime import date
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage, on_delete=models.PROTECT)
date = models.DateField(_("Date"), default=date.today)
def __str__(self):
return str(self.date)
This should be sufficent
from django.db import models
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage, on_delete=models.PROTECT)
date = models.DateField(auto_now_add=True))
def __str__(self):
return str(self.date)
And for the formatting stuff use the #property mentioned in stackoverflow.com/q/20229198/4107823 as commented by PetarP

Django date query from newest to oldest

I am building my first Django program from scratch and am running into troubles trying to print out items to the screen from newest to oldest.
My model has an auto date time field populated in the DB as so:
Model
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.utils import timezone
class TaskItem(models.Model):
taskn = models.CharField(max_length = 400)
usern = models.ForeignKey(User)
#Created field will add a time-stamp to sort the tasks from recently added to oldest
created_date = models.DateTimeField('date created', default=timezone.now)
def __str__(self):
return self.taskn
What is the line of code that would be abel to sort or print this information in order from newest creation to oldest?
Want to implement it into this call:
taskitems2 = request.user.taskitem_set.all().latest()[:3]
ordered_tasks = TaskItem.objects.order_by('-created_date')
The order_by() method is used to order a queryset. It takes one argument, the attribute by which the queryset will be ordered. Prefixing this key with a - sorts in reverse order.
By the way you also have Django's created_at field at your disposal:
ordered_tasks = TaskItem.objects.order_by('-created_at')
You can set your ordering in model Meta class. This will be the default ordering for the object,for use when obtaining lists of objects.
class TestModel(models.Model):
...
created_at = models.DateField()
....
class Meta:
ordering = ['-created_at']
Or you can apply ordering to specific queryset.
TestModel.objects.order_by('-created_at')