How to do this query using Django orm? - django-orm

I have a Profile model and Complain model both are connected to the inbuilt User model.I have to do a query using both in which Profile model have residence. I want to have a count, that how many complains are made from a particular residence. I can do it using SQL but I didn't know how to do it using Django.
SELECT users_profile.residence,count(user_id)from users_profile INNER JOIN chp_complain on(users_profile.user_id = chp_complain.complain_user_id)GROUP BY(user_id)
Complain Model:-
class Complain(models.Model):
complain_user = models.ForeignKey(User, on_delete=models.CASCADE)
complain_department=models.CharField(max_length=100)
complain_subject = models.CharField(max_length = 100,help_text = "Enter the complain subject")
department_head=models.CharField(max_length=100)
recepient=models.CharField(max_length=100)
complain_description=models.TextField(max_length=2000)
date_posted = models.DateTimeField(default = timezone.now)
NOT_VISITED = 'NV'
VISITED = 'V'
INPROCESS = 'IP'
COMPLETED = 'C'
status = (
(NOT_VISITED, 'NV'),
(VISITED, 'V'),
(INPROCESS, 'IP'),
(COMPLETED, 'C'),)
status=models.CharField(max_length=2,choices=status,)
Profile Model:-
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
UID =models.CharField(max_length=30,default = "000",help_text = "'Staff's fill their STAFF ID and student's fill their ROLL NO " )
MALE = 'M'
FEMALE = 'F'
Gender=((MALE, 'Male'),(FEMALE, 'Female'),)
Gender=models.CharField(max_length=6,choices=Gender,default=MALE,)
FIRST = '1st'
SECOND = '2nd'
THIRD = '3rd'
FOURTH = '4th'
NGH = 'NGH'
NON_HOSTELER = 'Non_hosteler'
TEACHER_QUARTER = 'Teacher_quarter'
residence = ((FIRST, 'First'),(SECOND, 'Second'),(THIRD, 'Third'),(FOURTH, 'Fourth'),(NGH,'NGH'),(NON_HOSTELER, 'Non_hosteler'),(TEACHER_QUARTER,'Teacher_quarter'))
residence = models.CharField(max_length=20,choices=residence,default=FIRST,)
room_no=models.CharField(max_length=10,default = "000")

I want to have a count, that how many complains are made from a particular residence you can write:
Complain.objects.values('complain_user__profile__residence').annotate(complains_count=Count('id'))
In your SQL query:
SELECT users_profile.residence,count(user_id)from users_profile INNER JOIN chp_complain on(users_profile.user_id = chp_complain.complain_user_id)GROUP BY(user_id)
You calculate how many users filed complaints from a particular residence. It can be calculated as follows:
User.objects.values('profile__residence').annotate(Count('id'))

Related

Dynamic NAV 2018 Web Service: Creating Sales Order Lines gets error "Standard Code Text does not exist...."

In Dynamic NAV 2018, I exposed page Sales Order (id 36) as web service, I'm following some guides to create Sales Order Header and Sales Order Lines, the Header can be created successfully, but the Sales Lines always get error "Standard Code Text does not exist..."
SOWS.Sales_Order_VS_Service testcreateSO = new SOWS.Sales_Order_VS_Service();
testcreateSO.UseDefaultCredentials = true;
SOWS.Sales_Order_VS SOEntity = new SOWS.Sales_Order_VS();
testcreateSO.Create(ref SOEntity);
SOEntity.Sell_to_Customer_No = "44094";
SOEntity.Store_No = "S9003";
SOEntity.Location_Code = "S9003";
testcreateSO.Update(ref SOEntity);
SOEntity.SalesLines = new SOWS.Sales_Order_Line[1];
SOEntity.SalesLines[0] = new SOWS.Sales_Order_Line();
testcreateSO.Update(ref SOEntity);
SOEntity.SalesLines[0].Type = SOWS.Type.Item;
SOEntity.SalesLines[0].TypeSpecified = true;
SOEntity.SalesLines[0].No = "208122";
SOEntity.SalesLines[0].Quantity = 1;
testcreateSO.Update(ref SOEntity);
System.Web.Services.Protocols.SoapException: 'The Standard Text does not exist. Identification fields and values: Code='208122''
Checking in table Sales Lines, a record of new order has been created but Type = 0 (means blank)
Document No_ Line No_ Sell-to Customer No_ Type No_ Location Code Document Type
SO210600017 10000 0 1
Please help
Solution
Instead of using only singe page Sales Order as web service, can expose page Sales Order Line as another web service, so full code as below:
SOWS.Sales_Order_VS_Service testcreateSO = new SOWS.Sales_Order_VS_Service();
testcreateSO.UseDefaultCredentials = true;
SOWS.Sales_Order_VS SOEntity = new SOWS.Sales_Order_VS();
testcreateSO.Create(ref SOEntity);
SOEntity.Sell_to_Customer_No = "44094";
SOEntity.Store_No = "S9003";
SOEntity.Location_Code = "S9003";
testcreateSO.Update(ref SOEntity);
//Using Sales Order Line page as web service from here
SOLinesWS.salesDocumentLines_Service saleslinesSV = new SOLinesWS.salesDocumentLines_Service
{
UseDefaultCredentials = true
};
SOLinesWS.salesDocumentLines saleslines = new SOLinesWS.salesDocumentLines();
saleslines.documentType = SOLinesWS.documentType.Order;
saleslines.documentTypeSpecified = true;
saleslines.documentNumber = SOEntity.No;
saleslines.type = SOLinesWS.type.Item;
saleslines.typeSpecified = true;
saleslines.number = "208122";
saleslines.quantity = 1;
saleslines.quantitySpecified = true;
saleslinesSV.Create(ref saleslines);

Distinct with joins

How do I get distinct rows based on the Last_Name field when my format is as follows:
public ActionResult Index()
{
ResumeDbEntities srd = new ResumeDbEntities();
List<M_Employees> First_Name = srd.M_Employees.ToList();
List<M_Employees> Last_Name = srd.M_Employees.ToList();
List<M_Employees> CurrentLaborCategory = srd.M_Employees.ToList();
List<M_Offices> Location_Number = srd.M_Offices.ToList();
List<M_Offices> City = srd.M_Offices.ToList();
List<M_Offices> State = srd.M_Offices.ToList();
List<S_Emp_Resume> Resume_Name = srd.S_Emp_Resume.ToList();
var multipleTbl = (from p in Resume_Name
join t in Last_Name on p.Employee_Rec_Key equals t.Employee_Rec_Key
join o in Location_Number on t.Office_Rec_Key equals o.Office_Rec_Key
where t.Employee_Rec_Key == 3633
select new MultipleClassRes { M_Employeesdetails = t, S_Emp_Resumedetails = p, M_Officesdetails = o});
return View(multipleTbl);
}
Newly working with MVC but included the auto number from one of the joins.

How to improve query with two contexts - MVC5, LINQ n EF

I have two contexts. In one of them i have two views of which i get cods related to an entity from the another context. This query is taking too long time. How to improve it?
var negociacoes = _db.Negociacoes.Include(o=> o.User).ToArray();
var produtos = _oriDb.Vw_Produtos.ToArray();
var clientesVendedor = _oriDb.Vw_ClientesVendedores.ToArray();
var query = from n in negociacoes
join p in produtos on n.ProdutoId equals p.ProdutoId
join c in clientesVendedor on n.ClienteId equals c.codigo_entidade
select new NegociacaoView
{
NegociacaoId = n.NegociacaoId,
ProdutoId = n.ProdutoId,
Produto = p.descricao,
ClienteId = n.ClienteId,
Cliente = c.razao_social,
Rca = n.Rca,
Quantidade = n.Quantidade,
Preco = n.Preco,
Situacao = n.Situacao,
UserId = n.User.UserName,
Atendente = n.Atendente,
CondicaoId = n.CondicaoId,
DataCriacao = n.DataCriacao,
DataLiberacao = n.DataLiberacao,
Observacao = n.Observacao,
User = n.User
};
return query.ToList();
There are a couple of ways to speed this up:
It helps to run the smallest most efficient query first, then use those results to constrain the following queries.
Defining a select list so the database doesn't have to materialize every column will speed things up and use less memory.
Unfortunately, no matter how you do it in LINQ, you will end up with sql that uses large IN statements. A sproc would give you access to temp tables and joins that would be even better.
var negociacoes = _db.Negociacoes.Include(o=> o.User).ToArray();
//Use results of first query to constrain the second two. You could maybe combine the second two into one query.
var clientIds = negociacoes.Select(x => x.ClienteId);
var productIds = negociacoes.Select(x => x.ProdutoId);
var produtos = _oriDb.Vw_Produtos
.Where(x => productIds.Contains(x.ProdutoId))
//add a select. You're only using two columns from this table.
//.Select(x => new { })
.ToArray();
var clientesVendedor = _oriDb.Vw_ClientesVendedores
.Where(x => clientIds.Contains(x.codigo_entidade))
//add a select. You're only using two columns from this table.
//.Select(x => new { })
.ToArray();
var query = from n in negociacoes
join p in produtos on n.ProdutoId equals p.ProdutoId
join c in clientesVendedor on n.ClienteId equals c.codigo_entidade
select new NegociacaoView
{
NegociacaoId = n.NegociacaoId,
ProdutoId = n.ProdutoId,
Produto = p.descricao,
ClienteId = n.ClienteId,
Cliente = c.razao_social,
Rca = n.Rca,
Quantidade = n.Quantidade,
Preco = n.Preco,
Situacao = n.Situacao,
UserId = n.User.UserName,
Atendente = n.Atendente,
CondicaoId = n.CondicaoId,
DataCriacao = n.DataCriacao,
DataLiberacao = n.DataLiberacao,
Observacao = n.Observacao,
User = n.User
};
return query.ToList();

How to search multi keywork in linq query

i have this code in homepage
CheckBox[] ch= new CheckBox[12];
ch[0] = ChkContextA;
ch[1]= ChkContextB;
ch[2]= ChkContextC;
ch[3]= ChkContextD;
ch[4]= ChkContextE;
ch[5]= ChkContextF;
ch[6]= ChkContextG;
ch[7]= ChkContextH;
ch[8]= ChkContextI;
ch[9]= ChkContextJ;
ch[10]= ChkContextK;
ch[11]= ChiContextL;
for (int i = 0; i < 11; i++)
if (ch[i].Checked) search += ch[i].Text + " ";
Response.Redirect("SearchEstate.aspx?content="+search);
and this code in SearchEstate
var content = Request.QueryString["content"];
RealEstateEntities db = new RealEstateEntities();
var query = from O in db.Owners
join E in db.Estates on O.OwnerID equals E.OwnerID
join P in db.Properties on E.PropertyID equals P.PropertyID
where P.Facilities.Contains(content)
select new
{
regdate = E.RegisterDate,
region = E.Region,
Estype = E.EstateType,
Fac = P.Facilities,
deal = P.DealType,
price = P.TotalCost,
img = E.Picture,
addrss = O.Address,
area = P.Area,
tel = P.TellNum,
bed = P.RoomNum,
park = P.ParikingNum
};
Repeater2.DataSource = query.OrderByDescending(x => x.regdate);
Repeater2.DataBind();
when user checked some checkbox "content" for example have this value:
SearchEstate.aspx?content=ContextB ContextE ContextJ
I Want search this values in Facility field in db
How can I do this? (Sorry for my bad English)
I have the feeling your are looking for something along the lines of this query:
var content = Request.QueryString["content"];
string[] contentArray = content.Split(' ');
//...
var query = //...
where P.Facilities.Any(f => contentArray.Contains(f.FacilityName))
//...
(or instead of FacilityName some other property of Facility)
But I am not sure.

How do I test a trigger with an approval process?

I have a trigger which initiates an approval process when certain criteria are met:
trigger AddendumAfterIHMS on Addendum__c (after update) {
for (integer i = 0; i<Trigger.new.size(); i++){
if(Trigger.new[i].RecordTypeId != '012V0000000CkQA'){
if(Trigger.new[i].From_IHMS__c != null && Trigger.old[i].From_IHMS__c == null){
ID addendumId = Trigger.new[i].Id;
// Start next approval process
Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest();
request.setObjectId(addendumId);
Approval.ProcessResult requestResult = Approval.process(request);
}
}
}
}
It works perfectly, but now i need to create a test class for it. I have created a class which brings the code up to 75% coverage, which is the minimum, but I'm picky and like to have 100% coverage on my code. The test class I have now gets stuck on the line request.setObjectId(addendumId); and doesn't move past it. The error I receive is:
System.DmlException: Update failed. First exception on row 0 with id a0CV0000000B8cgMAC; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AddendumAfterIHMS: execution of AfterUpdate
Here is the test class that I have written so far, most of the class actually tests some other triggers, but the important line which is throwing the error is the very last line update addendumTierFeature;
#isTest
private class AddendumTest {
static testMethod void myUnitTest() {
// Query Testing Account, will need ID changed before testing to place into production
Account existingAccount = [SELECT Id FROM Account LIMIT 1];
Model__c existingModel = [SELECT Id FROM Model__c WHERE Active__c = TRUE LIMIT 1];
Pricebook2 existingPricebook = [SELECT Id,Name FROM Pricebook2 WHERE IsActive = TRUE LIMIT 1];
List<Contact> existingContacts = [SELECT Id,Name FROM Contact LIMIT 2];
Contact existingContactPrimary = existingContacts[0];
Contact existingContactSecondary = existingContacts[1];
Opportunity newOpportunity = new Opportunity(
Name = 'New Opportunity',
Account = existingAccount,
CloseDate = Date.today(),
Order_Proposed__c = Date.today(),
StageName = 'Branch Visit - Not Responding',
Opportunity_Follow_Up__c = 'Every 120 Days',
LeadSource = 'Farm Lists',
Source_Detail__c = 'FSBO',
Model_Name__c = existingModel.Id,
Processing_Fee__c = 100.50,
Site_State__c = 'OR',
base_Build_Zone__c = 'OR',
Pricebook_from_Lead__c = existingPricebook.Name
);
insert newOpportunity;
//system.assert(newOpportunity.Id != null);
ID newOppId = newOpportunity.Id;
OpportunityContactRole contactPrimary = new OpportunityContactRole(
Role = 'Primary',
IsPrimary = true,
OpportunityId = newOppId,
ContactId = existingContactPrimary.Id
);
OpportunityContactRole contactSecondary = new OpportunityContactRole(
Role = 'Primary',
IsPrimary = false,
OpportunityId = newOppId,
ContactId = existingContactPrimary.Id
);
insert contactPrimary;
insert contactSecondary;
newOpportunity.Name = 'Different - Updating';
newOpportunity.Order_Accepted__c = Datetime.now();
update newOpportunity;
Addendum__c addendumCustomOption = new Addendum__c(
RecordTypeId = '012V0000000CkQA', //Pre Priced Custom Option
Opportunity__c = newOppId,
Item_Pre_Priced_Description__c = 'a1eV00000004DNu',
Reason__c = 'This is a reason',
Item__c = 'This is an Item',
Quantity__c = 1
);
Addendum__c addendumTierFeature = new Addendum__c(
RecordTypeId = '012V0000000Cjks', //Tier Feature
Opportunity__c = newOppId,
Category__c = 'Countertops',
Reason__c = 'This is a reason',
Item__c = 'This is an Item',
Quantity__c = 1
);
insert addendumCustomOption;
insert addendumTierFeature;
addendumCustomOption.Quantity__c = 2;
addendumTierFeature.Quantity__c = 2;
update addendumCustomOption;
update addendumTierFeature;
update newOpportunity;
addendumTierFeature.To_IHMS__c = system.now();
update addendumTierFeature;
addendumTierFeature.From_IHMS__c = system.now();
update addendumTierFeature;
}
}
Any help on this matter would be greatly appreciated. I believe the problem is in the way I am testing the approval process start. Is there by chance a special testing function for this?
After fiddling around for a little while I discovered that the error was actually tied into my approval process. I kept digging into the error logs until I got to the error: caused by: System.DmlException: Process failed. First exception on row 0; first error: MANAGER_NOT_DEFINED, Manager undefined.: []. This phrase indicates that there is no one defined for the next step in my approval process.
When I created the opportunity, I did not set the owner and somehow this created an opportunity which had an owner without a manager. The addendum was also created without an owner/manager. So when I tried to launch the next approval process, there was no manager to send the approval to and an error was thrown.