For loop in Django - django

I have two question. First question: Python script that shows me the precipitation for a certain period.For example, I'm getting an initial year-month and a final year-month.
Initial:
year:2000
month:3
Final
year1:2005
month:4
Now, instead of seeing:
2000/3,2000/4,2000/5,2000/6..........2005/1,2005/2,2005/3,2005/4
she works like this(look in the hooked picture):
2000/3, 2000/4, 2001/3, 2001/4........2005/3,2005/4.
I want to work for me like the first case.
def period_month_prec(year,month,year1,month1):
for i in range (year,year1+1,1):
for j in range(month,month1+1,1):
......................
Second question: How to write the output(picture) from the script in csv.fileenter image description here
This is what my views.py script looks like , which saves me only the first result:
def monthly_period(request):
if request.method == "POST" :
form = PeriodMonthlyForm(request.POST)
if form.is_valid():
data = form.cleaned_data
year = data.get('year')
month = data.get('month')
year1 = data.get('year1')
month1 = data.get('month1')
lon = data.get('lon')
lat = data.get ('lat')
inter = data.get('inter')
point = period_month_prec(year,month,year1,month1,lon,lat)
args = {'point':point}
response = HttpResponse(content_type='text/txt')
response['Content-Disposition'] = 'attachment; filename="precipitation.txt"'
writer = csv.writer(response)
writer.writerow([point])
return response
else:
form = PeriodMonthlyForm()
active_period_monthly = True
return render (request, 'carpatclimapp/home.html',{'form':form, 'active_period_monthly': active_period_monthly})

Ok, i have forms like this:
Forms
You set initial values(red color) and end interval(blue color). For this given interval, the lon and lat are defined for the point in which we want to perform interpolation. When you press the submit button, it starts with interpolation for a defined period. The loop problem is because it works only for the defined months (we see from the 2nd picture that it only works in the interval 1-6) but not for 7,8,9,10,11,12 months between these years.
Initial: year:2000, month:3
Final: year1:2001, month:4
for this she's doing it like this: 2000/3,2000/4,2001/3,2001/4
I do not want that, I want this: 2000/3,2000/4,2000/5,2000/6,2000/7.....2000/12,2001/1,2001/2,2001/3,2001/4.
this is me code :
def period_month_prec(year,month,year1,month1,lon,lat):
cnx = sqlite3.connect(DB1)
cursor = cnx.cursor()
table = 'monthly'
year = int(year)
year1 = int(year1)
month = int(month)
month1 = int(month1)
for i in range (year,year1+1,1):
for j in range(month,month1+1,1):
query = '''
SELECT dates, cell, prec FROM %s WHERE dates = "%s-%s" ;
''' % (table,i,j)
df = pd.read_sql_query(query, cnx)
tacka = '''SELECT id, lon, lat,country,altitude FROM %s;''' % 'grid1'
grid1 = pd.read_sql_query(tacka, cnx)
podaci = pd.merge(df,grid1,left_on='cell',right_on='id')
podaci_a = podaci.drop(['cell','id','country','altitude'],axis=1)
lon_n = podaci_a['lon'].values
lat_n = podaci_a['lat'].values
prec =podaci_a['prec'].values
x_masked, y_masked, prec_p = remove_nan_observations(lon_n, lat_n, prec)
xy = np.vstack([x_masked,y_masked]).T
xi = ([lon,lat])
inter_point = interpolate_to_points(xy,prec_p,xi, interp_type='linear'
return (i,j,lon,lat,inter_point)
The results that come out look like this:
loop with calculations
The second question was how to save these results(2nd picture) in the csv file, how to write correctly views.py. Currently she looks like this :
def monthly_period(request):
if request.method == "POST" :
form = PeriodMonthlyForm(request.POST)
if form.is_valid():
data = form.cleaned_data
year = data.get('year')
month = data.get('month')
year1 = data.get('year1')
month1 = data.get('month1')
lon = data.get('lon')
lat = data.get ('lat')
inter = data.get('inter')
point = period_month_prec(year,month,year1,month1,lon,lat)
args = {'point':point}
response = HttpResponse(content_type='text/txt')
response['Content-Disposition'] = 'attachment; filename="precipitation.txt"'
writer = csv.writer(response)
writer.writerow([point])
return response
else:
form = PeriodMonthlyForm()
active_period_monthly = True
return render (request, 'carpatclimapp/home.html',{'form':form, 'active_period_monthly': active_period_monthly})
I hope I'm a little clearer now

Related

Django queryset from raw SQL

I want an equivalent of this sql query in Django
SELECT Gender, ServCode
FROM [openimisproductTestDb_16_08_22].[dbo].[tblInsuree]
JOIN [openimisproductTestDb_16_08_22].[dbo].[tblServices] ON [openimisproductTestDb_16_08_22].[dbo].[tblInsuree].AuditUserID = [openimisproductTestDb_16_08_22].[dbo].[tblServices].AuditUserID
WHERE Gender = 'F'
AND ServCode = 'F4'
What I have tried:
def assisted_birth_with_cs_query(user, **kwargs):
date_from = kwargs.get("date_from")
date_to = kwargs.get("date_to")
hflocation = kwargs.get("hflocation")
format = "%Y-%m-%d"
date_from_object = datetime.datetime.strptime(date_from, format)
date_from_str = date_from_object.strftime("%d/%m/%Y")
date_to_object = datetime.datetime.strptime(date_to, format)
date_to_str = date_to_object.strftime("%d/%m/%Y")
dictBase = {
"dateFrom": date_from_str,
"dateTo": date_to_str,
}
dictGeo = {}
if hflocation and hflocation!="0" :
hflocationObj = HealthFacility.objects.filter(
code=hflocation,
validity_to__isnull=True
).first()
dictBase["fosa"] = hflocationObj.name
claimItem = Insuree.objects.filter(
validity_from__gte = date_from,
validity_to__lte = date_to,
**dictGeo,
gender = 'F'
).count()
data = Service.objects.filter(code = 'F4').count() | Insuree.objects.filter(gender = 'F').count()
dictGeo['health_facility'] = hflocationObj.id
dictBase["post"]= str(data)
return dictBase
I tried like that but the one just adds when I want the women included in the insured table and the F4 code contained in the service table. both tables have the auditUserID column in common
It would be great if you could add the models to better see the relations between Insuree and Service. Assuming it's a 1-M, I'd go with this query:
Service.objects.filter(code='F4', insuree__gender='F').count()

Updating database based on previous csv file uploads - delete - create - or update Python/Dajngo

Please need help with the following
I am trying to update database in comparison to previous uploaded csv file. I need to update all fields except the vin if it changes (vin is the unique value), delete the item if it is no longer in the csv file and create one if one is new
vin. stock_no make model trim miles
12345789098765432 4535 honda civic lx 89000
j4j4jj49098765432 3453 toyota corolla DX 54555
12345345438765432 6254 ford mustang es 101299
When I change any value and the csv is uploaded it makes a duplicate:
def upload_file__view(request):
form = form(request.POST or None, request.FILES or
None)
company = Comp_info.objects.last()
if form.is_valid():
form.save()
obj = c.objects.get(activated=False)
with open(obj.file_name.path, 'r+') as f:
reader = c.reader(f)
for i, row in enumerate(reader):
if i==0:
pass
else:
# row = "".join(row)
# row = row.replace(",", " ")
# row = row.split()
print(row)
print(type(row))
vin = row[0].upper()
condition = row[1].replace("U", "Used").replace("N", "New")
stock_no = row[2]
year = int(row[5])
make = row[3]
model = row[4]
trim = row[6]
mileage = row[8]
mpg_city = row[18]
mpg_hwy = row[19]
engine = row[9]
transmission = row[12]
fuel_type = row[11]
vehicle_type = row[7]
drive_type = row[20].replace("4X2", "2WD").replace("4X4", "4WD")
exterior_color = row[15]
interior_color = row[16]
price = row[13].replace("0", "")
description = row[22]
features_2 = row[21]
images_data = row[23]
raw_images_list = images_data.split(',')
images_list = [""] * 25
for x in range(image_count):
if x == 25:
break
images_list[x] = raw_images_list[x]
for x in images_list:
print(x)
if images_list[0] == "":
images_list[0] = "https://www.beverlyhillscarclub.com/template/images/ina_f.jpg"
car_photo = images_list[0]
car_photo_1 = images_list[1]
car_photo_2 = images_list[2]
car_photo_3 = images_list[3]
car_photo_4 = images_list[4]
car_photo_5 = images_list[5]
car_photo_6 = images_list[6]
car_photo_7 = images_list[7]
car_photo_8 = images_list[8]
car_photo_9 = images_list[9]
car_photo_10 = images_list[10]
car_photo_11 = images_list[11]
car_photo_12 = images_list[12]
car_photo_13 = images_list[13]
car_photo_14 = images_list[14]
car_photo_15 = images_list[15]
car_photo_16 = images_list[16]
car_photo_17 = images_list[17]
car_photo_18 = images_list[18]
car_photo_19 = images_list[19]
car_photo_20 = images_list[20]
car_photo_21 = images_list[21]
car_photo_22 = images_list[22]
car_photo_23 = images_list[23]
car_photo_24 = images_list[24]
# notes = pip._vendor.requests(images_list[0], stream=True)
#car_photo = row[23]
# user = User.objects.get(username=row[3])
Cars.objects.update_or_create(
vin = vin,
condition = condition,
stock_no = stock_no,
year = year,
make = make,
model = model,
trim = trim,
mileage = mileage,
mpg_city = mpg_city,
engine = engine,
transmission = transmission,
fuel_type = fuel_type,
vehicle_type = vehicle_type,
drive_type = drive_type,
exterior_color = exterior_color,
interior_color = interior_color,
price = price,
description = description,
company_name = company.company_name,
address = company.company_address,
city = company.city,
state = company.state,
zip = company.zip_code,
phone_number = company.phone_number,
email = company.fax_number,
features_2 = features_2,
car_photo = downloadFile(car_photo),
car_photo_1 = downloadFile(car_photo_1),
car_photo_2 = downloadFile(car_photo_2),
car_photo_3 = downloadFile(car_photo_3),
car_photo_4 = downloadFile(car_photo_4),
car_photo_5 = downloadFile(car_photo_5),
car_photo_6 = downloadFile(car_photo_6),
car_photo_7 = downloadFile(car_photo_7),
car_photo_8 = downloadFile(car_photo_8),
car_photo_9 = downloadFile(car_photo_9),
car_photo_10 = downloadFile(car_photo_10),
car_photo_11 = downloadFile(car_photo_11),
car_photo_12 = downloadFile(car_photo_12),
car_photo_13 = downloadFile(car_photo_13),
car_photo_14 = downloadFile(car_photo_14),
car_photo_15 = downloadFile(car_photo_15),
car_photo_16 = downloadFile(car_photo_16),
car_photo_17 = downloadFile(car_photo_17),
car_photo_18 = downloadFile(car_photo_18),
car_photo_19 = downloadFile(car_photo_19),
car_photo_20 = downloadFile(car_photo_20),
car_photo_21 = downloadFile(car_photo_21),
car_photo_22 = downloadFile(car_photo_22),
car_photo_23 = downloadFile(car_photo_23),
car_photo_24 = downloadFile(car_photo_24)
#car_photo = car_photo,
# quantity = int(row[2]),
# salesman = user
)
obj.activated = True
obj.save()
data = {
'form' : form,
'now' : now,
}
return render(request, 'uploads.html', data)
Thanks in advance for any help!
Thank you
Step 1
An empty list was created to compare with uploaded data:
imported_cars = []
Step 2
Created a filter of unique value (primary Key) and checked if it existed and used the method get to update items. Created car (item variable) to update or create ubject.
if Cars.objects.filter(vin=vin).exists():
car = Cars.objects.get(vin=vin)
Step 3
Used else statement to create item if it did not exist.
else:
car = Cars.objects.create(vin=vin, condition=condition...)
Last, out of the loop populated empty list with updated and created cars and deleted items that were in the database but not in the csv file.
imported_cars_vin_numbers = [car.vin for car in imported_cars]
for car in Cars.objects.all():
if car.vin not in imported_cars_vin_numbers:
car.delete()
Special thanks and credit to Zack Plauché who was extremely helpful and professional in helping me and teaching me how to solve this issue.
Your issue is in the model.py
you should write the Cars object with the following.
vin = models.CharField(primary_key=True, editable=False)
Confirm this works, since I am suggesting solution without actually seeing the model.py
This should handle the update aspect of your logic. The part where you delete a vin if its not in the CSV will have to be done with new process I don't see written here.But a suggestion would be to clear the DB and repopulate, or create function that compares DB with CSV and delete object if not in CSV.

Django queryset for current year

I have my query written to get some thing from database and display on my website that query is getting all the data from db but what if i want to get the data particular to current year only
def get(self, request, *args, **kwargs):
filters = self.get_filters()
result = Model.objects.all().filter(*filters).distinct().aggregate(
t=Sum('t'),
b=Sum('b'),
)
result2 = Model.objects.all().filter(*filters).distinct().aggregate(
past_due=Sum('balance', filter=Q(due_date__lt=timezone.now()))
)
zero = Decimal('0.00')
total = result['t'] or zero
balance = result['b'] or zero
past_due = result2['past_due'] or zero
amount_received = t - b
I think filter=Q(due_date__year=datetime.now().date().year) should work for you, if I understand your question correctly.
This worked for me
result = Model.objects.all().filter(*filters, created__year=datetime.now().year).distinct().aggregate(
t=Sum('t'),
b=Sum('b'),
)
result2 = Model.objects.all().filter(*filters, created__year=datetime.now().year).distinct().aggregate(
past_due=Sum('balance', filter=Q(due_date__lt=timezone.now()))
)

Set initial values in form passing parameters (kwargs) with view

I want to prefill a form with values taken in a table.
First I pass the PK relative to the line where I wan't to get values and build the kwargs list:
views.py
def NavetteToFicheCreateView(request, pk):
navette = Navette.objects.get(id=pk)
ref = navette.id
attribute_set = navette.famille.pk
cost = navette.cost
qty = navette.qty
etat = navette.etat
etat_ebay = navette.etat.etat_ebay
ean = get_last_ean()
form = NavetteToFicheForm(
request.POST,
ref=ref,
attribute_set=attribute_set,
cost=cost,
qty=qty,
etat=etat,
etat_ebay=etat_ebay,
ean=ean,
)
[...]
then I retrieve the kwargs in the form.py and setup my initial values
class NavetteToFicheForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.ref = kwargs.pop('ref', 'noref')
self.attribute_set = kwargs.pop('attribute_set', 9999)
self.cost = kwargs.pop('cost', 0)
self.qty = kwargs.pop('qty', 0)
self.etat = kwargs.pop('etat', 0)
self.etat_ebay = kwargs.pop('etat_ebay', 9999)
self.ean = kwargs.pop('ean', 9999)
super(NavetteToFicheForm, self).__init__(*args, **kwargs)
self.fields['ref'].initial = self.ref
self.fields['attribute_set'].initial = self.attribute_set
self.fields['cost'].initial = self.cost
self.fields['qty'].initial = self.qty
self.fields['etat'].initial = self.etat
self.fields['etat_ebay'].initial = self.etat_ebay
self.fields['ean'].initial = self.ean
[...]
My problem : some fields like "ref" or "attribute_set" are foreignKeys and are not transmitted when i display the form.
For checking my values :
print(self.ref)
print(self.attribute_set)
output
34
2
noref
9999
questions :
Why does the "print" displays 2 couples of values ? This looks like as if the "noref" and "999" are taken in account.
Why if i set manually 34 and 2 values, it works ?
self.fields['ref'].initial = 34
self.fields['attribute_set'].initial = 2
There's maybe a better way of doing this but I don't know it yet .

How to save calculated variables in django database and load it after?

I'm making a simple calculation app, but I want to save calculated variables in the database so I can load them after I need them. Thank you
def showvideo(request):
allvideos = Video.objects.all()
form = VideoForm(request.POST or None)
if form.is_valid():
sirina = form.cleaned_data.get('sirina')
visina = form.cleaned_data.get('visina')
category = form.cleaned_data.get('category')
roletne = form.cleaned_data.get('roletne')
okapnice = form.cleaned_data.get('okapnice')
materijal = form.cleaned_data.get('materijal')
komore = form.cleaned_data.get('komore')
krila = form.cleaned_data.get('krila')
#Example
a = 20 + sirina
b = 30 + visina
c = 50 + roletne
## I want to save those variables in database and load them after
## in template
form.save()
context={'form':form}
return render(request,'index.html',context)