query for daily count in django - python

I have a log model as
models.py
class Log(models.Model):
module = models.CharField(null=False, blank=False,default=None, max_length=20)
mobile = models.CharField(null=False, blank=False,max_length=15)
incoming_text = models.TextField(null=False, blank=False,)
outgoing_text = models.TextField(null=False, blank=False,)
shortcode = models.CharField(null=False, blank=False, max_length=6)
network = models.CharField(null=True, blank=False, max_length=15)
user = models.CharField(null=True, blank=False, max_length=15)
created_on = models.DateTimeField(auto_now_add=True, null=False, blank=False)
campaign = models.CharField(null=False, blank=False, max_length=30)
now I have to generate the query in django such that the total daily count on the basis of created_on field is reqquired. how can I acheive it in django?

Log.objects.filter(pub_date=datetime.date.today()).count() . This should work

Related

Django filterset and Django rest framework not working as expected

I have created a Django filter set to filter data, some fields are filtered with relationships.
When I never filter with the endpoint, it just returns all data instead of filtered data, what could be wrong here?
This is my endpoint filterer :
http://127.0.0.1:5000/api/v1/qb/questions/?paper=26149c3b-c3e3-416e-94c4-b7609b94182d&section=59bdfd06-02d4-4541-9478-bf495dafbee1&topic=df8c2152-389a-442f-a1ce-b56d04d39aa1&country=KE
Below is my sample :
from django_filters import rest_framework as filters
class QuestionFilter(filters.FilterSet):
topic = django_filters.UUIDFilter(label='topic',
field_name='topic__uuid',
lookup_expr='icontains')
sub_topic = django_filters.UUIDFilter(label='sub_topic',
field_name='topic__sub_topic__uuid',
lookup_expr='icontains')
paper = django_filters.UUIDFilter(label='paper',
field_name='paper__uuid',
lookup_expr='icontains')
section = django_filters.UUIDFilter(label='section',
field_name='section__uuid',
lookup_expr='icontains')
subject = django_filters.UUIDFilter(label='subject',
field_name="paper__subject__id",
lookup_expr='icontains'
)
year = django_filters.UUIDFilter(label='year',
field_name='paper__year__year',
lookup_expr="icontains")
country = django_filters.CharFilter(label='country',
field_name="paper__exam_body__country",
lookup_expr='icontains')
class Meta:
model = Question
fields = ['topic', 'section', 'paper', 'sub_topic', 'subject', 'year',
'country']
Then my view is like this :
class QuestionView(generics.ListCreateAPIView):
"""Question view."""
queryset = Question.objects.all()
serializer_class = serializers.QuestionSerializer
authentication_classes = (JWTAuthentication,)
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = QuestionFilter
Then the models attached to the filter are as below :
class Question(SoftDeletionModel, TimeStampedModel, models.Model):
"""Questions for a particular paper model."""
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
mentor = models.ForeignKey(User, related_name='question_mentor', null=True,
on_delete=models.SET_NULL)
paper = models.ForeignKey(Paper, max_length=25, null=True,
blank=True, on_delete=models.CASCADE)
question = models.TextField(
_('Question'), null=False, blank=False)
section = models.ForeignKey(QuestionSection,
related_name='section_question',
null=True, on_delete=models.SET_NULL)
topic = models.ForeignKey(Course, related_name='topic_question',
null=True, on_delete=models.SET_NULL)
question_number = models.IntegerField(_('Question Number'), default=0,
blank=False, null=False)
image_question = models.ImageField(_('Image question'),
upload_to='image_question',
null=True, max_length=900)
answer_locked = models.BooleanField(_('Is Answer locked'), default=True)
status = models.CharField(max_length=50, choices=QUESTION_STATUSES,
default=ESSAY)
address_views = models.ManyToManyField(CustomIPAddress,
related_name='question_views',
default=None, blank=True)
bookmarks = models.ManyToManyField(User, related_name='qb_bookmarks',
default=None, blank=True)
def __str__(self):
return f'{self.question}'
Paper Model
class Paper(SoftDeletionModel, TimeStampedModel, models.Model):
"""Paper model."""
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
subject = models.ForeignKey(Subject, related_name='subject',
null=True, on_delete=models.SET_NULL)
mentor = models.ForeignKey(User, related_name='paper_mentor', null=True,
on_delete=models.SET_NULL)
year = models.DateField(_('Year'), blank=False, null=False)
grade_level = models.ForeignKey(ClassGrade, related_name='grade_paper',
null=True, on_delete=models.SET_NULL)
exam_body = models.ForeignKey(ExamBody, related_name='exam_body_paper',
null=True, on_delete=models.SET_NULL)
number_of_questions = models.IntegerField(_('No of questions'),
blank=False, null=False)
number_of_sections = models.IntegerField(_('No of sections'),
blank=False, null=False)
color_code = ColorField(format='hexa', default='#33AFFF', null=True)
class Meta:
ordering = ['created']
def __str__(self):
return f'{self.subject.name} ({self.year})'
QuestionSection Model :
class QuestionSection(SoftDeletionModel, TimeStampedModel, models.Model):
"""Question paper sections e.g Section A, B, C etc."""
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
section = models.CharField(
_('Question Section'), max_length=100, null=False, blank=False)
def __str__(self):
return f'{self.section}'
class Course(SoftDeletionModel, TimeStampedModel, models.Model):
"""
Topic model responsible for all topics.
"""
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
title = models.CharField(
_('Title'), max_length=100, null=False, blank=False)
overview = models.CharField(
_('Overview'), max_length=100, null=True, blank=True)
description = models.CharField(
_('Description'), max_length=200, null=False, blank=False
)
country = CountryField()
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
topic_cover = models.ImageField(
_('Topic Cover'), upload_to='courses_images',
null=True, blank=True, max_length=900)
grade_level = models.ForeignKey(
ClassGrade, max_length=25, null=True,
blank=True, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
ranking = models.IntegerField(
_('Ranking of a Topic'), default=0, help_text=_('Ranking of a Topic')
)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "Topics"
ordering = ['ranking']

Django: how to upload media files to different folders?

I want to save file in automatically created folder related with Employee id_number like:
media->employee->attachments->emp001->emp001.pdf
models.py
from django.db import models
class Employee(models.Model):
id_number = models.CharField(primary_key=True, null=False, blank=False, unique=True, max_length=15)
full_name = models.CharField(max_length=255, null=False, blank=False)
name_with_initials = models.CharField(max_length=255, null=False, blank=False)
surname = models.CharField(max_length=255, null=False, blank=False)
phone = models.CharField(max_length=15, null=False, blank=False)
dob = models.DateField(null=False, blank=False)
gender = models.CharField(max_length=10, null=False, blank=False)
email = models.EmailField()
address = models.CharField(max_length=255, null=False, blank=False)
class EmployeeAttachments(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
cv = models.FileField(upload_to=f'employee/attachments/', max_length=100)
can any one tell me how to do this in django, django-rest-framework
This will change a path of cv on EmployeeAttachments according to your Employee id
def facility_path(instance, filename):
return f'attachments/employee/emp{instance.employee.id}/emp{instance.employee.id}.pdf'
class EmployeeAttachments(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
cv = models.FileField(upload_to=facility_path, max_length=500)

How do I attach the user's order to the product issued Django

Ok, so I have this application where the users make an order for a Category through the app. Every category contains products. And what I want to do is when a product is issued to the user the order status for the order made by the user should change from 1(approved) to 4(issued) and the product name should be added in the order table to confirm the product that was issued to that request.
How do I do that in Django? Below are my models
class Category(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Product(models.Model):
pro_name = models.CharField(max_length=100, blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
issue_to = models.ForeignKey('Order',default='', on_delete=models.CASCADE,blank=True, null=True)
serial_num = models.CharField(max_length=100, blank=True, null=True)
model_num = models.CharField(max_length=100, blank=True, null=True)
storage_size = models.CharField(max_length=50, blank=True, null=True)
memory_size = models.CharField(max_length=50, blank=True, null=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, blank=True, null=True)
receive_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_by = models.CharField(max_length=50, blank=True, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=False, null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Order(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
pro_name = models.ForeignKey(Product, on_delete=models.CASCADE, null=True,related_name='product')
staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
order_quantity = models.PositiveIntegerField(null=True)
department = models.CharField(max_length=50, choices=DEPARTMENT, null=True)
order_status = models.IntegerField(default=0)
approve_quantity = models.IntegerField(default='1', blank=True, null=True)
transaction_id = models.CharField(default=uuid.uuid4().hex[:8].upper(), max_length=50, editable=False)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
Currently what I do is after a particular product has been issued to a user I have to go to the order table and change the order status to 4(issued) which is hectic especially when the orders are plenty.

How to filter product by its Attribute in Django - Django?

I'm working on a Django Ecommerce project where product has several attributes like. size, color( A single product can have multiple attributes with different size and color). No i'm trying to filter products using django_filters but unable to filter by its attributes.
Product Model:
class Product(models.Model):
variations = (
('None', 'None'),
('Size', 'Size'),
)
name = models.CharField(max_length=200, unique=True)
store = models.ManyToManyField(Store)
slug = models.SlugField(null=True, blank=True, unique=True, max_length=500)
sku = models.CharField(max_length=30, null=True)
tax = models.IntegerField(null=True, blank=True)
stock = models.CharField(max_length=10, null=True)
variations = models.CharField(choices=variations, max_length=20)
short_description = models.CharField(max_length=500, null=True)
details = RichTextUploadingField(null=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
discounted_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
image = models.ImageField(upload_to='product/images', default='product.png', null=True,
blank=True)
image_one = models.ImageField(upload_to='product/images', null=True, blank=True)
image_two = models.ImageField(upload_to='product/images', null=True, blank=True)
image_three = models.ImageField(upload_to='product/images', null=True, blank=True)
image_four = models.ImageField(upload_to='product/images', null=True, blank=True)
image_five = models.ImageField(upload_to='product/images', null=True, blank=True)
tags = models.ManyToManyField(Tags)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True,
related_name='products')
status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive',
'Inactive')))
brand = models.ForeignKey(Brand, on_delete=models.PROTECT, blank=True, null=True)
offer = models.ForeignKey(Offer, on_delete=models.CASCADE, null=True,
blank=True) # This is used only for filtration
Product attribute model
class ProductAttribute(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
size = models.ForeignKey(Size, on_delete=models.CASCADE, null=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2, validators=
[MinValueValidator(1)])
discounted_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
stock = models.CharField(max_length=10, null=True)
The standard approach would be to define the attributes in the "Product" model. However, if you insist on doing this, the code will be:
filtered_ProductAttributes=ProductAttribute.objects.filter(size="12")
products=[filtered_ProductAttribute.product for filtered_ProductAttribute in filtered_ProductAttributes]
As you can see the code seems very inefficient, therefore, as was suggested in the beginning put the attributes in the "Product" model and you will have:
products=Product.objects.filter(size="12")
Refining your model will help you to filter.
With my experience following model approach will be more suitable:
class Attributes(models.Model):
name = models.CharField(max_length=50, default=None)
slug = models.SlugField(max_length=200, unique=True,null=True)
class AttributeTerms(models.Model):
name = models.CharField(max_length=50, blank =True)
attribute = models.ForeignKey(Attributes, on_delete=models.CASCADE)
class Products(models.Model):
name = models.CharField(max_length=250,null=True, blank=True,)
slug = models.SlugField(max_length=200, unique=True,null=True)
class ProductAttribute(models.Model):
product = models.ForeignKey(Products,on_delete=models.CASCADE, related_name='attributes', default=None)
attributes = models.ForeignKey(Attributes,on_delete=models.CASCADE, related_name='attributes', default=None)
values = models.ForeignKey(AttributeTerms, on_delete=models.CASCADE, related_name='attributes', default=None)
class ProductVariant(models.Model):
product = models.ForeignKey(Products,on_delete=models.CASCADE)
variant = models.ForeignKey(ProductAttribute,on_delete=models.CASCADE, null = True, default=None)
stock = models.IntegerField(default=None)
stock_threshold = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
sku = models.CharField(max_length= 250, default=None)
sale_price = models.DecimalField(max_digits=10, decimal_places=2)

Pk fields always ends up in resulting query GROUP BY clause

I have my model hierarchy defined as follows:
class Meal(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
discount_price = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=4)
normal_price = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=4)
available_count = models.IntegerField(blank=False, null=False)
name = models.CharField(blank=False, null=False, max_length=255)
active = models.BooleanField(blank=False, null=False, default=True)
class Order(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
number = models.CharField(max_length=64, blank=True, null=True)
buyer_phone = models.CharField(max_length=32, blank=False, null=False)
buyer_email = models.CharField(max_length=64, blank=False, null=False)
pickup_time = models.DateTimeField(blank=False, null=False)
taken = models.BooleanField(blank=False, null=False, default=False)
class OrderItem(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items')
meal = models.ForeignKey(Meal, on_delete=models.CASCADE)
amount = models.IntegerField(blank=False, null=False, default=1)
I'm trying to get some statistics about orders and I came up with django orm call that looks like this:
queryset.filter(created_at__range=[date_start, date_end])\
.annotate(price=Sum(F('items__meal__discount_price') * F('items__amount'), output_field=DecimalField()))
.annotate(created_at_date=TruncDate('created_at'))\
.annotate(amount=Sum('items__amount'))\
.values('created_at_date', 'price', 'amount')
The above however doesn't give me the expected results, because for some reason the id column still ends up in the GROUP BY clause of sql query. Any help with that?
To make it work I had to do the following:
qs.filter(created_at__range=[date_start, date_end])\
.annotate(created_at_date=TruncDate('created_at'))\
.values('created_at_date')\
.annotate(price=Sum(F('items__meal__discount_price') * F('items__amount'),
output_field=DecimalField()))
.annotate(amount=Sum('items__amount'))
Which kind of makes sense - I pull only the created_at field, transform it and then annotate the result with two other fields.

Categories