How to generate oracle specific queries django - django

How can I get Django to produce/submit the exact query below:
SELECT "MESSAGE"."MSG_NO", "MESSAGE"."MSG_TYPE", "MESSAGE"."DIRECTION", "MESSAGE"."SESSION_NO", "MESSAGE"."SEQUENCE_NO", "MESSAGE"."REF_SESSION", "MESSAGE"."REF_SEQUENCE", "MESSAGE"."ACKTIME", "MESSAGE"."ACKNAKSTATUS", "MESSAGE"."PRIORITY", "MESSAGE"."DELIVMONITOR", "MESSAGE"."OBSOLESCENCE", "MESSAGE"."DISPOSITION", "MESSAGE"."TRAILER", "MESSAGE"."BYPASSED", "MESSAGE"."RESPONSE_QUEUE", "MESSAGE"."SOURCE_QUEUE", "MESSAGE"."QUEUE", "MESSAGE"."QUEUE_PRIORITY", "MESSAGE"."DATE_CREATED", "MESSAGE"."DATE_ROUTED", "MESSAGE"."INPUT_FILE", "MESSAGE"."OUTPUT_FILE", "MESSAGE"."STATUS1", "MESSAGE"."STATUS2", "MESSAGE"."STATUS3", "MESSAGE"."USERID", "MESSAGE"."TMSTAMP"
FROM "MESSAGE"
WHERE ("MESSAGE"."DATE_CREATED" >= (SYSDATE-3)
AND "MESSAGE"."DIRECTION" = 0
AND "MESSAGE"."STATUS1" = 0)
The below code produces a query that does not work:
Message.objects.using(queue_db_env).filter(STATUS1=0, DIRECTION=0, DATE_CREATED__gte=time_threshold)
Below is the query produced by the code above and it does not work when I run it manually:
SELECT "MESSAGE"."MSG_NO", "MESSAGE"."MSG_TYPE", "MESSAGE"."DIRECTION", "MESSAGE"."SESSION_NO", "MESSAGE"."SEQUENCE_NO", "MESSAGE"."REF_SESSION", "MESSAGE"."REF_SEQUENCE", "MESSAGE"."ACKTIME", "MESSAGE"."ACKNAKSTATUS", "MESSAGE"."PRIORITY", "MESSAGE"."DELIVMONITOR", "MESSAGE"."OBSOLESCENCE", "MESSAGE"."DISPOSITION", "MESSAGE"."TRAILER", "MESSAGE"."BYPASSED", "MESSAGE"."RESPONSE_QUEUE", "MESSAGE"."SOURCE_QUEUE", "MESSAGE"."QUEUE", "MESSAGE"."QUEUE_PRIORITY", "MESSAGE"."DATE_CREATED", "MESSAGE"."DATE_ROUTED", "MESSAGE"."INPUT_FILE", "MESSAGE"."OUTPUT_FILE", "MESSAGE"."STATUS1", "MESSAGE"."STATUS2", "MESSAGE"."STATUS3", "MESSAGE"."USERID", "MESSAGE"."TMSTAMP"
FROM "MESSAGE"
WHERE ("MESSAGE"."DATE_CREATED" >= 2018-09-15 12:47:43.784709
AND "MESSAGE"."DIRECTION" = 0
AND "MESSAGE"."STATUS1" = 0)
This is due to "MESSAGE"."DATE_CREATED" >= 2018-09-15 12:47:43.784709 , query only works when I swap out the DATE_CREATE clause with "MESSAGE"."DATE_CREATED" >= (SYSDATE-3)
My views.py has the code of:
class MessageList(APIView):
def get(self, request, queue_db_env, queue_name, queue_id, format=None):
#
# time_threshold = datetime.now() - timedelta(hours=36)
now = timezone.now()
time_threshold = now - datetime.timedelta(hours=36)
print(time_threshold.timestamp())
str_time_threshold = time_threshold.timestamp()
#
messages = Message.objects.using(queue_db_env).filter(STATUS1=0, DIRECTION=0, DATE_CREATED__gte=time_threshold)
print(messages.query)
serializer = MessageSerializer(messages, many=True)
return Response({"Queue": queue_name, "Queue_ID": queue_id, "Queue_Messages": serializer.data})
My models.py is:
from django.db import models
class Message(models.Model):
MSG_NO = models.IntegerField(primary_key=True,)
MSG_TYPE = models.IntegerField()
DIRECTION = models.IntegerField()
SESSION_NO = models.IntegerField()
SEQUENCE_NO = models.IntegerField()
REF_SESSION = models.IntegerField()
REF_SEQUENCE = models.IntegerField()
ACKTIME = models.DateTimeField(max_length = 7)
ACKNAKSTATUS = models.IntegerField()
PRIORITY = models.CharField(max_length = 1)
DELIVMONITOR = models.IntegerField()
OBSOLESCENCE = models.IntegerField()
DISPOSITION = models.IntegerField()
TRAILER = models.IntegerField()
BYPASSED = models.IntegerField()
RESPONSE_QUEUE = models.IntegerField()
SOURCE_QUEUE = models.IntegerField()
QUEUE = models.IntegerField()
QUEUE_PRIORITY = models.IntegerField()
DATE_CREATED = models.DateTimeField()
DATE_ROUTED = models.DateTimeField()
INPUT_FILE = models.IntegerField()
OUTPUT_FILE = models.IntegerField()
STATUS1 = models.IntegerField()
STATUS2 = models.IntegerField()
STATUS3 = models.IntegerField()
USERID = models.CharField(max_length = 8)
TMSTAMP = models.DateTimeField()
I want to filter on last 3 days on DATE_CREATED colument
I am using an oracle database and I am failing to filter on date.

time_threshold = now - datetime.timedelta(hours=36)
There are twenty-four hours in a day. So 36 hours = 1.5 days. If you want to filter on the last three days you need
timedelta(hours=72)

Related

how can i use django filter with multiple value select

I want to filter my data based on city , how can i filter my data if the user choose more than one city using django filter
class games(generics.ListAPIView):
queryset = Game.objects.filter(start_date__gte=datetime.today())
serializer_class=GameSerializers
filter_backends = [DjangoFilterBackend,filters.OrderingFilter]
filterset_fields = ['id','city','level']
game model
class Game(models.Model):
city = models.CharField(max_length=255)
gender = models.ForeignKey(Gender,on_delete=models.CASCADE)
level = models.ForeignKey(Level,on_delete=models.CASCADE)
host = models.ForeignKey(Host,on_delete=models.CASCADE)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
fees = models.IntegerField()
indoor = models.BooleanField()
capacity = models.IntegerField()
age_from = models.IntegerField()
age_to = models.IntegerField()
description = models.CharField(max_length=255)
earned_points = models.IntegerField()
created_at = models.DateTimeField(default=django.utils.timezone.now)
image = models.ImageField(upload_to="GameImage",null=True)
history = HistoricalRecords()
Game.objects.filter(city__in=['Paris', 'London'])
Something like that ?
I'm not sure if this gonna work but try this:
filterset_fields = ['id','city__in','level']

Django ORM query for filtering product price between two number is not working properly

class Product(models.Model):
product_name = models.CharField(max_length=255,unique=True)
slug = models.SlugField(max_length=255)
brand = models.CharField(max_length=255)
price = models.CharField(max_length=255)
product_image_1 = models.ImageField(upload_to = 'photos/product',blank = False)
product_image_2 = models.ImageField(upload_to = 'photos/product', blank = False)
product_image_3 = models.ImageField(upload_to = 'photos/product', blank = False)
product_image_4 = models.ImageField(upload_to = 'photos/product',blank = False)
product_description = models.TextField()
category_id = models.ForeignKey(Categories,on_delete=models.CASCADE)
subcategory_id = models.ForeignKey(SubCategories, on_delete=models.CASCADE)
stock = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.product_name
def get_url(self):
return reverse('product_detail',args = [self.category_id.slug , self.subcategory_id.slug,
self.slug ])
'''view'''
val=request.POST.get('value')
val = re.findall("\d+", val) # code to get all inigers from string
min_price = int(val[0])
max_price = int(val[1])
print(min_price)
print(max_price)
***product = Product.objects.filter(category_id = categories,is_active =
True,price__gte = min_price, price__lte = max_price)***
when i give value greater than max_value product object returns null object
I want all objects between the two min_value and max_value

Having issue in handling multipart form data in django rest framework

I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. multipart/form-data is used because there is an image field that needs to be sent in arrays.
But I got the following error.
Category field is required
The data is sent like this
name: Soap
category[0]: 7
category[1]: 23
brand: 7
collection: 11
availability: in_stock
warranty: no_warranty
service: cash_on_delivery
rating: 3
best_seller: true
top_rated: true
featured: true
main_product_image: (binary)
merchant: 2
variants[0][product_id]: fgfdg
variants[0][price]: 127
variants[0][quantity]: 1
variants[0][color]: red
variants[0][size]: M
variants[0][variant_availability]: not_available
variants[0][variant_image]: (binary)
variants[1][product_id]: fgfdg
variants[1][price]: 127
variants[1][quantity]: 1
variants[1][color]: red
variants[1][size]: M
variants[1][variant_availability]: not_available
variants[1][variant_image]: (binary)
The same issue is with the variants.
My models:
class Variants(models.Model):
product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True)
price = models.DecimalField(decimal_places=2, max_digits=20,default=500)
size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True)
color = models.CharField(max_length=70, default="not applicable",blank=True,null=True)
variant_image = models.ImageField(upload_to="products/images", blank=True,null=True)
thumbnail = ImageSpecField(source='variant_image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product
variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available')
class Meta:
verbose_name_plural = "Variants"
def __str__(self):
return self.product_id
#Product Model
class Product(models.Model):
merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
category = models.ManyToManyField(Category, blank=False)
sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
featured = models.BooleanField(default=False) # is product featured?
best_seller = models.BooleanField(default=False)
top_rated = models.BooleanField(default=False)
tags = TaggableManager(blank=True) # tags mechanism
name = models.CharField(max_length=150,unique=True)
main_product_image = models.ImageField(upload_to="products/images", null=True, blank=True)
thumbnail = ImageSpecField(source='main_product_image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
slug = models.SlugField(max_length=200,blank=True)
description = RichTextField(blank=True)
#picture = models.ImageField(upload_to="products/images", null=True, blank=True)
picture = models.ManyToManyField(ImageBucket,null=True,blank=True,verbose_name="Add extra 3 images")
rating = models.IntegerField(choices=((1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5))
)
availability = models.CharField(max_length=70, choices=AVAILABILITY, default='in_stock')
warranty = models.CharField(max_length=100, choices=WARRANTY, default='no_warranty')
services = models.CharField(max_length=100, choices=SERVICES, default='cash_on_delivery')
variants = models.ManyToManyField(Variants,related_name='products')
My view:
class ProductAddAPIView(CreateAPIView):
permission_classes = [IsAuthenticated]
parser_classes = [MultiPartParser,JSONParser,FormParser]
# queryset = Product.objects.all()
serializer_class = AddProductSerializer
Here I have used parser class just in case if it works.
Updated Code:
class AddProductSerializer(serializers.ModelSerializer):
id = serializers.PrimaryKeyRelatedField(read_only=True)
variants = VariantSerializer(many=True)
slug = serializers.SlugField(read_only=True)
class Meta:
model = Product
fields = ['id','merchant','featured', 'top_rated','category','brand','collection','sub_category',
'name','slug','description', 'main_product_image','best_seller','picture',
'rating','availability','warranty','services','variants']
#depth = 1
def create(self, validated_data):
#user = self.context['request'].user
picture_data = validated_data.get('picture')
merchant = validated_data.get('merchant')
category_data = validated_data.get('category')
featured = validated_data.get('featured')
top_rated = validated_data.get('top_rated')
brand = validated_data.get('brand')
collection = validated_data.get('collection')
sub_category = validated_data.get('sub_category')
name = validated_data.get('name')
description = validated_data.get('description')
main_product_image = validated_data.get('main_product_image')
best_seller = validated_data.get('best_seller')
rating = validated_data.get('rating')
availability = validated_data.get('availability')
warranty = validated_data.get('warranty')
services = validated_data.get('services')
#variants_logic
variants_data = validated_data.get('variants')
#breakpoint()
print(variants_data)
# from pudb import set_trace;set_trace()
#products-logic
product = Product.objects.create(featured=featured,top_rated=top_rated,
brand=brand,collection=collection,sub_category=sub_category,
name=name,description=description,
main_product_image=main_product_image,
best_seller=best_seller,rating=rating,
availability=availability,warranty=warranty,
services=services,merchant=merchant)
product.save()
product.category.set(category_data)
# product.variants.set(variants_data)
product.save()
for variants_data in variants_data:
abc = Variants.objects.create(**variants_data)
product.variants.add(abc)
product.save()
return product

Sub query result in Django not looping from drop down select box

This is the error am getting:
QuerySet.annotate() received non-expression(s): 17
What I want is a subquery that will do something similar to the
select * from inecdb.announced_pu_results
where polling_unit_uniqueid in
(
select uniqueid from polling_unit
where lga_id = (select uniqueid from lga where uniqueid= 17)
);
The subquery
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=Subquery(Unit.objects.filter(lga_id=obj1)))
is not displaying any result please can any one help
This is my view
if request.method == 'POST':
selected_item = request.POST.get('item_id') #This is from html select box
obj = Lga.objects.get(lga_id=selected_item)
obj1 = obj.lga_id
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=Subquery(Unit.objects.filter(lga_id=obj1)))
for obt in obj3:
print(obt.party_score) #I want looping results here
This is my Model
from django.db import models
from django.urls import reverse
#from django.urls import reverse
class Unit(models.Model):
uniqueid = models.IntegerField(primary_key=True)
polling_unit_id = models.IntegerField(blank=False)
ward_id = models.IntegerField(default=False)
lga_id = models.IntegerField(default=False)
uniquewardid = models.IntegerField(default=True)
polling_unit_number = models.CharField(max_length=50, unique=True)
polling_unit_name = models.CharField(max_length=51)
#pulling_unit_number = models.CharField(max_length=50)
polling_unit_description = models.CharField(max_length=300)
lat = models.CharField(max_length=255)
long = models.CharField(max_length=255)
entered_by_user = models.CharField(max_length=50)
date_entered = models.DateTimeField(blank=False)
user_ip_address = models.CharField(max_length=50)
def get_absolute_url(self):
#return f"/products/{self.id}/"
return reverse("polling:inec-pull-result", kwargs={"uniqueid": self.uniqueid})
class Lga(models.Model):
uniqueid = models.AutoField(primary_key=True)
lga_id = models.IntegerField()
lga_name = models.CharField(max_length=50)
state_id = models.IntegerField()
lga_description = models.TextField(blank=True, null=True)
entered_by_user = models.CharField(max_length=50)
date_entered = models.DateTimeField()
user_ip_address = models.CharField(max_length=50)
class Meta:
db_table = 'lga'
class Article(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
active = models.BooleanField(default=True)
You need to make sure that the queryset you use for the subquery returns just one column, use values() for that. Note that Subquery isn't needed:
units = Unit.objects.filter(lga_id=obj1).values('uniqueid')
obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=units)
Read the documentation for the in lookup for a more detailed explanation of passing a QuerySet to in.
This also works:
obj3 = Pu_results.objects.filter(
polling_unit_uniqueid__in = Subquery(
Unit.objects.values('uniqueid').filter(lga_id=obj1)
)
)

Django group by only using users_id and get all other fields from model

views.py
condition = Q(vendor_id=vendor_id)
sum_invoice_qry = Sum('amount', filter=Q(transaction_type=1))
sum_payment_qry = Sum('amount', filter=Q(transaction_type=2))
qs = Transaction.objects.values('users_id').annotate(sum_invoice=sum_invoice_qry).annotate(sum_payment=sum_payment_qry).filter(condition)
=> I need to group by users_id and all other fields from model,
- But, currently it is making this query:
SELECT `tbl_transactions`.`users_id`, SUM(CASE WHEN `tbl_transactions`.`transaction_type` = 1 THEN `tbl_transactions`.`amount` ELSE NULL END) AS `sum_invoice`, SUM(CASE WHEN `tbl_transactions`.`transaction_type` = 2 THEN `tbl_transactions`.`amount` ELSE NULL END) AS `sum_payment` FROM `tbl_transactions` WHERE (`tbl_transactions`.`vendor_id` = 3544 AND `tbl_transactions`.`billing_type` = ) GROUP BY `tbl_transactions`.`users_id`, `tbl_transactions`.`date_time`, `tbl_transactions`.`date_added` ORDER BY `tbl_transactions`.`date_time` DESC, `tbl_transactions`.`date_added` DESC
=> Why the date_time and date_added is appended in group by? how to remove them
=> How to get all others fields, like vendor_id, amount... from models
models.py
from django.contrib.auth import get_user_model
from django.db import models
# Create your models here.
class Transaction(models.Model):
users = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)
vendor_id = models.IntegerField(blank=True)
transaction_id = models.CharField(max_length=100,blank=True)
#transaction_type = models.CharField(max_length=100,blank=True)
TYPE_CHOICES = ((0, 'Select Transaction Type'),(1, 'Invoice'), (2, 'Payment'))
transaction_type = models.IntegerField(default=0,blank=True,choices=TYPE_CHOICES)
amount = models.DecimalField(max_digits=15,decimal_places=2)
out_std_amount = models.DecimalField(max_digits=15,decimal_places=2,blank=True)
description = models.TextField(blank=True)
attachment = models.ImageField(upload_to="images/transactions/%Y/%m/%d",blank=True)
quantity = models.IntegerField(default=0)
billing_type = models.CharField(max_length=50,blank=True)
date_time = models.DateTimeField(auto_now=False)
added_by = models.IntegerField(blank=True)
date_added = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
super(Transaction, self).save(*args, **kwargs)
class Meta:
db_table = 'tbl_transactions'
ordering = ['-date_time','-date_added']
def __unicode__(self):
return self.transaction_id