Peewee how to set query's operators and logics by variable? - peewee

I want to build query dynamically with peewee.
Example query:
User.select()
.where(
(User.full_name=="test") |
(User.email=="test")
)
Is there any possible like that?
op1 = "=="
op2 = "!="
logic = "|"
User.select()
.where(
(User.full_name op1 "test") logic
(User.email op2 "test")
)

You can use the operator module.
import operator
name_is_test = operator.eq(User.full_name, 'test')
email_is_test = operator.eq(User.email, 'test')
User.select().where(operator.or_(name_is_test, email_is_test)

Related

SQL Variable that means the same as *

I'm trying to build a query that searches based on a series of different criteria, however sometimes you will only have to use some of the criteria.
I'd like to be able to do something like below where, to change the query I would only need to change the bits in bold at the top of the query, so as only to search by criteria1 and criteria2 without having to change any of the rest of the query. Thanks
Declare #criteria1 as varchar(1),#criteria2 as varchar(1),#criteria3 as varchar(1)
Set #criteria1 = 'a'
Set #criteria2 = 'b'
Set criteria3 = '*'
/*I don't want to change anything below this point*/
Select * from table where
a = #criteria1
b = #criteria2
c = #criteria3
You can use conditional logic. If you want to use *, then:
Select *
from table
where (a = #criteria1 or #criteria1 = '*') and
(b = #criteria2 or #criteria2 = '*') and
(c = #criteria3 or #criteria3 = '*');
More typically, NULL would be used for this purpose -- because it works for any type and is not confused with any other "real" value:
Select *
from table
where (a = #criteria1 or #criteria1 is null) and
(b = #criteria2 or #criteria2 is null) and
(c = #criteria3 or #criteria3 is null);
Finally, SQL Server is going to do a full table scan in general with such conditions (the mixing of and and or). You might want to construct the query dynamically if you want the query to use indexes. However, if you are using one-character columns, then the indexes would not be particularly selective, so that might not apply in this particular case.

How do I write a conditional (IF DATA EXISTS) LINQ statement without repetition?

I need to write a Linq query where the condition like this:
when data exists then the join will be INNER JOIN
when data is not exists then the join will be LEFT JOIN.
bool ifexists = db.Users.Any(u => u.id== 1);
IQueryable<modelname> query;
if(ifexists == true)
{
query=my inner join linq;
query = from s in query select s;
return query.ToList();
}
else
{
query=my left join linq;
query = from s in query select s;
return query.ToList();
}
Now how I can write this Linq? Is there any way to write this linq in a single Linq statement - I don't want to write the linq twice?
You can conditionally compose on an IQueryable before evaluating it against the database - this will allow you to at least partially DRY up the common actions on the different legs of your branching:
var query = db.SomeTable
.AsQueryable() // Not needed if `db.SomeTable` is already a Queryable
.Where(x => ** common predicates on x ** ));
// NB : Do not materialize here!
if(exists) // Don't need == true
{
query = query
.Where(x => ** branch 1 predicates **));
}
else
{
query = query
.Where(x => ** branch 2 predicates **);
}
return query
.Select(q => ** common fields to project **)
.OrderBy(q => ** common ordering **)
.ToList(); // Materialize right at the end
You Want like That?
bool ifexists = db.Users.Any(u => u.id== 1);
var query=ifexists==true ? (my inner join linq) : (my left join linq);
return query.ToList();
First create object of of database Context named **Objcontext**
now hold the variable in var the query would be like following
var Result = from a in Objcontext.tbl1 where !Objcontext.tbl2.Any(m=>(m.sid==a.aid)&&(m.mid==80))
select a;
If data is exists in the databse it will cheack using !Objcontext
I hope it will helpfull

Need Equivalent LINQ Query for the following SQL Server Query

I am looking for the equivalent LINQ query for the following Query.
SELECT SUM (Cost) FROM [Vulpith_Test2].[dbo].tbl_MilestonesForOngoingSeeker]
WHERE ([Post_Title_ID] = '3251'
and [List_Title_ID]='1180')
and (PaymentStatus='1' or PaymentStatus='3');
int sumofCost = dbContext.tbl_MilestonesForOngoingSeeker.Where(a => a.Post_Title_ID == "3251" && a.List_Title_ID == "1180" && (a.PaymentStatus == 1 || a.PaymentStatus == 3)).Sum(a => a.Cost);

How to use Django models in for loop?

Query = 'com pu'
Query = Query.split()
busi = ""
for data in Query:
busi += Business.objects.filter(Keywords__icontains=data)
When I use '+' symbol after busi variable for add all data according to filter that give error
Exception Type: TypeError
Exception Value:Can't convert 'QuerySet' object to str implicitly
How can I achieve that different Query part which split by that all give different-2 data and and both data in single busi object
from django.db.models import Q
Query = Query.split()
query = Q()
for data in Query:
query |= Q(keyword_name__icontains=data)
Business= Business.objects.filter(query)
Instead use &:
busi = None
q = Business.objects.filter(Keywords__icontains=data)
if busi is None:
busi = q
else:
busi = busi & q

TYPO3: exec_SELECTquery with where clause

The following select returns an empty result set, although it shoudn't:
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'tx_xmluploader_xml_import_tree', 'xml_import_id='.$xml_import_id);
$xml_import_id is set. And it works if I remove the where clause..
Thanks
I still don't understand why it doesn't work.. A simple workaround suggested by a coleague:
// select all from the db
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'tx_xmluploader_xml_import_tree');
while( $entry = $GLOBALS['TYPO3_DB']->sql_fetch_assoc() )
{
if( $entry['xml_import_id'] == $xml_import_id ) {
....
}
}
First, make sure the following is set in localconf.php:
$TYPO3_CONF_VARS['SYS']['sqlDebug'] = '1';
$TYPO3_CONF_VARS['FE']['debug'] = '1';
Then try
$res = $GLOBALS['TYPO3_DB']->SELECTquery('*', 'tx_xmluploader_xml_import_tree', 'xml_import_id='.$xml_import_id);
t3lib_div::debug($res);
Result is the output of the query in the frontend. You can then execute it in MySQL for debugging.
a) make sure $xml_import_id actually has a value (one which is in the database as well)
b) Try this:
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'*',
'tx_xmluploader_xml_import_tree',
"xml_import_id='".$xml_import_id."'"
);
How do you process the result?
How does your expected $xml_import_id value look like?
cu
Roman

Resources