How to do a sequential query in a flask database - flask

as said in the title I'm supposed to query a database(SQLAlchemy) in a sequential manner: most of the data come from a checkbox in the HTML, I know that I can just do all the queries in one line but, here the problem: I've to query only the value that are going to be True, and obviously I can't foresee how many. So I'm asking if any of you knows a method to do so correctly, moreover I didn't find anything about nulling the booleans that are not True. Thanks for helping me!
Here is the code, I'm sure that there are not problem in the Database or in the HTML, but it just about how to do so.
if request.method == 'POST':
post_city = str(request.form['city'])
post_nation = str(request.form['nation'])
post_tools = request.form.get('fitness_tools')
post_pub = request.form.get('pub_presence')
post_games = request.form.get('games')
post_crowded = request.form.get('crowded')
post_fountain = request.form.get('fountain')
list_of_parks1 = Parks.query.filter_by(city=post_city, nation=post_nation).all()
if post_tools:
list_of_parks2 = Parks.query.filter_by(fitness_tools=post_tools).all()
if post_pub:
list_of_parks3 = Parks.query.filter_by(pub_presence=post_pub).all()
if post_games:
list_of_parks4 = Parks.query.filter_by(children_games=post_games).all()
if post_crowded:
list_of_parks5 = Parks.query.filter_by(crowded=post_crowded).all()
if post_fountain:
list_of_parks6 = Parks.query.filter_by(fountain=post_fountain).all()
list_of_parks = Parks.query.filter_by(city=post_city, nation=post_nation).all()
if list_of_parks:
session['parks_list'] = list_of_parks.id_park

Related

How to fix Django N+1 problem when you need to get data from a set of objects

I created a function and I wrote a query that results in N+1 Problem how to fix it
code
sponsors = CustomUser.objects.filter(user_type = 2, is_deleted = False)
for s in sponsors:
s.sponsor_detail = Sponsor.objects.get_or_create(user = s, is_deleted = False)
Would be nice if you included the models, but I guess sponsor_details is a ForeignKey. In this case you should use select_related:
sponsors = (CustomUser.objects
.filter(user_type = 2, is_deleted = False)
.select_related('sponsor_detail'))

django filter data and make union of all data points to assignt to a new data

My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]

Two django ORM query that should do same thing are doing different thing

take a look at these 2 function following:
def get_recommended_products_IT_WORKS(request):
carrello = get_basket(request)
articoli_carrello = Articolo.objects.filter(
variantearticolo__rigareferenza__referenza__paginavendita_referenza__rigacarrello__carrello=carrello)
TEMP = Referenza.objects.filter(rigareferenza__variante_articolo__articolo__in=articoli_carrello)
recommended_products = RecommendedProduct.objects.exclude(paginavendita_referenza__referenza__in=TEMP)
return recommended_products
def get_recommended_products_IT_DOESNT_WORK(request):
carrello = get_basket(request)
articoli_carrello = Articolo.objects.filter(
variantearticolo__rigareferenza__referenza__paginavendita_referenza__rigacarrello__carrello=carrello)
recommended_products = RecommendedProduct.objects.exclude(
paginavendita_referenza__referenza__rigareferenza__variante_articolo__articolo__in=articoli_carrello)
return recommended_products
To me, it seems that they should return the same results, but it's not working this way.
The former works like I need and the latter not.
Can you give me some hints? Thank you.

Subsonic 3 Save() then Update()?

I need to get the primary key for a row and then insert it into one of the other columns in a string.
So I've tried to do it something like this:
newsObj = new news();
newsObj.name = "test"
newsObj.Save();
newsObj.url = String.Format("blah.aspx?p={0}",newsObj.col_id);
newsObj.Save();
But it doesn't treat it as the same data object so newsObj.col_id always comes back as a zero. Is there another way of doing this? I tried this on another page and to get it to work I had to set newsObj.SetIsLoaded(true);
This is the actual block of code:
page p;
if (pageId > 0)
p = new page(ps => ps.page_id == pageId);
else
p = new page();
if (publish)
p.page_published = 1;
if (User.IsInRole("administrator"))
p.page_approved = 1;
p.page_section = staticParent.page_section;
p.page_name = PageName.Text;
p.page_parent = parentPageId;
p.page_last_modified_date = DateTime.Now;
p.page_last_modified_by = (Guid)Membership.GetUser().ProviderUserKey;
p.Add();
string urlString = String.Empty;
if (parentPageId > 0)
{
urlString = Regex.Replace(staticParent.page_url, "(.aspx).*$", "$1"); // We just want the static page URL (blah.aspx)
p.page_url = String.Format("{0}?p={1}", urlString, p.page_id);
}
p.Save();
If I hover the p.Save(); I can see the correct values in the object but the DB is never updated and there is no exception.
Thanks!
I faced the same problem with that :
po oPo = new po();
oPo.name ="test";
oPo.save(); //till now it works.
oPo.name = "test2";
oPo.save(); //not really working, it's not saving the data since isLoaded is set to false
and the columns are not considered dirty.
it's a bug in the ActiveRecord.tt for version 3.0.0.3.
In the method public void Add(IDataProvider provider)
immediately after SetIsNew(false);
there should be : SetIsLoaded(true);
the reason why the save is not working the second time is because the object can't get dirty if it is not loaded. By adding the SetIsLoaded(true) in the ActiveRecord.tt, when you are going to do run custom tool, it's gonna regenerate the .cs perfectly.

filter using Q object with dynamic from user?

In my views.py I have a method:
#......
def get_filter_result(self, customer_type, tag_selected):
list_customer_filter=[]
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
for customer_filter in customers_filter:
customer_filter.list_authorize_sale_type = sale_type_selected(customer_filter.authorize_sale_type)
list_customer_filter.append(customer_filter)
return list_customer_filter
**My case tag_selected is the checkbox values that user checked
I have a problems with tag_selected(is the list=1,2,3,...) that pass from my url
/?customer_type=TDO&tag=2 ===>filter okay
/?customer_type=TDO&tag=3 ===>filter okay
?customer_type=TDO&tag=2,3 ===>How Can I add And condition in filter?
for example
if len(tag_selected)==1:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
else:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected[0])
Q(tag__id=tag_selected[1])
Q(tag__id=tag_selected[2])
...
)
This works for both single and multiple conditions:
idseq = request.POST['tag'].split(',')
tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq))
Customers.objects.filter(..., tag_qs)