I have to filter data in Many2one field - filter

I have to models related to employees, one with contracts
class Contract(models.Model):
_name = 'hr.employee.contract'
_description = "employee contract model"
_rec_name = 'begin_date'
_order = 'begin_date desc'
type = fields.Many2one(string='Contract Type', comodel_name='hr.employee.contract_type')
category = fields.Many2one(string='Contract Category', comodel_name='hr.employee.contract_category')
begin_date = fields.Date(string='Begin Date')
end_date = fields.Date(string='End Date')
work_place = fields.Many2one(comodel_name='hr.employee.vessel', string='Work Place')
enterprise = fields.Char(related='work_place.enterprise.name', string='Enterprise')
sick_leave_reason = fields.Char(string='Sick Leave Reason')
employee = fields.Many2one(comodel_name='hr.employee', string='Employee ID', ondelete='cascade')
crew_member = fields.Many2one(string='Crew Member', comodel_name='hr.employee.crew_member')
internal_contract_id = fields.Integer(string='Internal Contract Id')
contract_code = fields.Integer(string='Contract Code')
And another model in whick I have to store the different work places for a certain contract. Both models are shown as tree list inside the employee card.
class Assignement(models.Model):
_name = 'hr.employee.assignement'
_description = "Employees assignement model"
contract_id = fields.Many2one(comodel_name='hr.employee.contract', string='Contrato')
employee = fields.Many2one(comodel_name='hr.employee', string='Employee ID')
work_place = fields.Many2one(comodel_name='hr.employee.vessel', string='Work Place')
begin_date = fields.Date(string='Begin Date')
end_date = fields.Date(string='End Date')
As it should work, if I edit the employee card which has a certaint number of contracts linked, when I am going to introduce an assignement, when I click on the field contract it should show only contracts of the employee a I am editing.
Help please.
Best regards

Related

Get value from the ListView

can anyone help me with my codes. I want to display the max amount of the fields amount from other .py
and display it on the form view.
Right now with that codes, im getting only the sequence number of the list, not the inputted amount.
**custom_item.py**
class Amount(models.Model):
_name = "custom.item"
_description = "Item List"
_order = 'create_date desc, id desc'
Item_lists_id = fields.Many2one('custom.item', "Items", required=True)
amount = fields.Integer("Amount", store=True)
**custom_account.py**
class Account(models.Model):
_name = "custom.account"
_description = "Account List"
_order = 'create_date desc, id desc'
item_amount_ids = fields.One2many('custom.item', 'account_id', "Item Summary:")
Items_count = fields.Integer("Count Items", compute='_get_grade_count')
amount_max = fields.Integer("High amount:", compute='_get_item_amount')
#api.depends('item_amount_ids')
def _get_item_amount(self):
for rec in self:
rec.amount_max = max(rec.item_amount_ids)

get list from a class to fill taxtbox in other class by linq

how to get just special 2 attributes from a table to other table( and placement in related textbox) by LINQ??
public string srcht(ACTIVITIES sn)
{
db db = new db();
var q = (from i in db.costumers.Where(i => i.id== sn.id)select i.name).ToList();
return q.Single();
}
public string srcht(ACTIVITIES sn)
{
db db = new db();
var q = (from i in db.costumers.Where(i => i.id== sn.id)select i.family).ToList();
return q.Single();
}
i did linq twice to fill 2 textboxes by name and family in other table. can i do it by one LINQ?
So you have an Activity in sn, and you want the Name and the Family of all Customers that have an Id equal to sn.Id.
var result = db.Customers.Where(customer => customer.Id == sn.Id)
.Select(customer => new
{
Name = customer.Name,
Family = customer.Family,
});
In words: in the database, from the table of Customers, keep only those Customers that have a value for property Id that equals the value of sn.Id. From the remaining Customers select the values of Name and Family.
If you expect that there will only be at utmost one such customer (so if Id is the primary key), just add:
.FirstOrDefault();
If you think there will be several of these customers, add:
.ToList();
The result will be an object, or a list of objects of some anonymous type with two properties: Name and Family.
If you want to mix the Name and the Family in one sequence of strings, which I doubt, consider to put the Name and the Family in an array. Result is sequence of arrays of strings. To make it one array of Strings, use SelectMany:
var result = db.Customers
.Where(customer => customer.Id == sn.Id)
.Select(customer => new string[]
{
customer.Name,
customer.Family,
})
.SelectMany(customer => customer);

How would one create summary columns in query results using Linq-to-SQL?

Let's say we have these tables:
CAR
ID Name
1 Mustang
2 Taurus
CAR_PART
ID CAR_ID PART_NUMBER
1 1 M772
2 1 A443
3 2 Z889
CAR_COLOR
ID CAR_ID COLOR_NAME
1 1 Red
2 1 Blue
3 2 Yellow
We need to use Linq-to-SQL to get this result:
CAR_ID CAR_NAME CAR_PART_LIST CAR_COLOR_LIST
1 Mustang M772,A443 Red,Blue
How would this be accomplished? I have a new class created with the result column names, and figure a select new MyClass{}; at the end would be good, but am not sure how to handle the multiple groupings for the CAR_PART_LIST and CAR_COLOR_LIST columns.
Any ideas?
edit: here is what I have so far:
from car in db.CAR
join part in db.CAR_PART on car.ID equals part.CAR_ID
join color in db.CAR_COLOR on car.ID equals color.CAR_ID
where car.ID = 1
select new MySearchResult{
CAR_ID = car.ID,
CAR_NAME = car.Name,
CAR_PART_LIST = ?,
CAR_COLOR_LIST = ?
}
public class MySearchResult{
public int CAR_ID { get; set; }
public string CAR_NAME { get; set; }
public string CAR_PART_LIST { get; set; }
public string CAR_COLOR_LIST { get; set; }
public MySearchResult() { }
}
Using the obvious String extension method:
public static string Join(this IEnumerable<string> s, string sep) => String.Join(s, sep);
You can compute the answer by using group join on each related table:
var ans = from car in db.CAR
join part in db.CAR_PART on car.ID equals part.CAR_ID into partj
join color in db.CAR_COLOR on car.ID equals color.CAR_ID into colorj
where car.ID == 1
select new MySearchResult {
CAR_ID = car.ID,
CAR_NAME = car.Name,
CAR_PART_LIST = partj.Select(p => p.PART_NUMBER).Join(","),
CAR_COLOR_LIST = colorj.Select(c => c.COLOR_NAME).Join(",")
};
Do you have foreign keys set up for db.CAR_PART and db.CAR_COLOR? If so, that linq-to-sql will automatically give you properties for the joins. So, it becomes:
var q = from car in db.Car
where car.ID == 1
select new MySearchResult
{
CAR_ID = car.ID,
CAR_NAME = car.Name,
CAR_PART_LIST = String.Join(",", car.CAR_PARTs.Select(cp=>cp.PART_NUMBER))
CAR_PART_LIST = String.Join(",", car.CAR_COLORs.Select(cp=>cp.COLOR_NAME))
};
So you have a table of CarParts, where every CarPart has a CarId and a PartNumber; and you have a table of CarColours, where every CarColour has a Carid and a ColourName.
I assume you do not support invisible cars, so every car has at least one part, and one colour.
You want a sequence of all CarIds, each CarId with the CarName, a list of all CarParts belonging to this CarId(= that have this CarId as foreign key) and a list of all ColourNames belonging to this CarId (again using the foreign key.
To do this, first we get all CarIds with their CarParts and all CarIds with their ColourNames, then we can Join the results on common CarId.
If you think there might be cars without parts or without colours, you need to do a 'Full outer Join' instead of a normal Join. This is not part of standard LINQ, but you can write the extension function yourself. See LINQ Full Outer Join
After the join on common CarId, we Join the result with your Cars on CarId
var partsGroupedByCarId = carParts.GroupBy( // make groups of carParts
carPart => carPart.CarId); // with common CarId as Key
var coloursGroupedByCarId = carColours.GroupBy( // make groups of carColours
carColour => carColour.CarId);, // with common CarId as Key
var joinResult = partsGroupedByCarId.Join( // Join the two groups
coloursGroupedByCarId,
partGroup => partGroup.Key, // from each group of parts take the key (= CarId)
colourGroup => // from each group of colours take the key (= CarId)
(partGroup, colourGroup) => new // when they match make a new object
{
CarId = partGroup.Key, // with the common CarId
CarParts = partGroup // all partNumbers of the car with CarId
.Select(item => item.PartNumber),
CarColours = colourGroup // all colourNames of the car with carId
.Select(item => item.ColourName),
});
Finally a Join of the Cars with all their Colours and Parts:
var result = Cars.Join(joinResult, // Join all cars with the joinResult
car => Id, // from every car take the id
joinedItem => joinedItem.CarId, // from every joinedItem take the CarId
(car, joinedItem) => new // for every car with its matching joinedItem
{ // make a new object
Id = car.Id,
Name = car.Name,
Parts = joinedItem.CarParts.ToList(),
Colours = joinedItem.CarColours.ToList(),
});
TODO: consider creating one big LINQ statements. As all statements use deferred execution I don't think this will improve efficiency. It certainly will decrease readability.
I writed it here dotnetfiddle please check it out:
var q = from car in cars
join part in carparts on car.ID equals part.CAR_ID into parts
join color in carcolors on car.ID equals color.CAR_ID into clrs
where car.ID == 1
select new MySearchResult{
CAR_ID = car.ID,
CAR_NAME = car.Name,
CAR_PART_LIST = String.Join(",",parts.Select(p => p.PART_NUMBER)),
CAR_COLOR_LIST = String.Join(",",clrs.Select(c => c.COLOR_NAME))};
foreach (var item in q)
Console.WriteLine("{0} {1} {2} {3}",
item.CAR_ID,
item.CAR_NAME,
item.CAR_PART_LIST,
item.CAR_COLOR_LIST);

odoo one2many list remove duplicates items

i have developed a module of purchase in odoo 10 community when i make a cammand of products i want to disable duplicate choose of product in widget one2many list as in the image below:
enter image description here
i want to prevent duplicate entry in the products list here is the code of my command module:
class PalBl(models.Model):
_name = 'pal.bl'
name = fields.Char('Reference', required=True)
supplier = fields.Many2one('pal.vendor', required=True)
date = fields.Date('Date', required=True)
totalHt = fields.Float('Total HT', store=True, readonly=True, compute='_get_tot')
totalTtc = fields.Float('Total TTC', store=True, readonly=True, compute='_get_tot')
items_id = fields.One2many('pal.prs.com', 'prod_id')
dateliv = fields.Date('Date de livraison prévue')
nb_pr = fields.Integer('Total de Produit')
state = fields.Selection([(1, 'En attente'), (2, 'Reglée')], 'type', default=1)
_sql_constraints = [('item_code_uniq', 'unique(items_id.name.code)', "le code d'un produit doit etre unique !")]
and this the code of the products:
class PalPrcom(models.Model):
_name = 'pal.prs.com'
name = fields.Many2one('pal.stock', 'Désignation', required=True)
code = fields.Char('Ref produit', store=True, readonly=True, compute='_getref', inverse='_gedef')
quantity = fields.Integer('Quantité', required=True, default=1)
price = fields.Float('Prix achat HT', store=True, readonly=True, compute='_getref')
tva = fields.Integer('TVA')
remise = fields.Integer('Remise')
prod_id = fields.Many2one('pal.bl')
_sql_constraints = [ ('quantity_gt_zero', 'CHECK (quantity>0)', 'La quantité de produit doit etre supérieur à zéro!')
]
You can use two for loops which will iterate over your one2many field and check for duplicates
This will work.
_sql_constraints = [('order_name', 'unique (relation_id,field_name_1,field_name_2)',
'Duplicates are not allowed!')]

Return one Element from List using LINQ

I have a list that contains 3 variables, expense, salary and year. I would like to return all expenses from the list using LINQ. Writing a foreach loop would suffice but I was hoping to archive something more efficient using LINQ.
I'm thinking something like this:
List<Company> ListCompanies = new List<Company>();
Company company1 = new Company() { Expense = 200, Salary = 1000, Year = new DateTime(2014, 1, 1).ToString("yyyy/mm/dd") };
Company company2 = new Company() { Expense = 300, Salary = 800, Year = new DateTime(2014, 2, 1).ToString("yyyy/mm/dd") };
Company company3 = new Company() { Expense = 500, Salary = 1400, Year = new DateTime(2014, 3, 1).ToString("yyyy/mm/dd") };
ListCompanies.Add(company1);
ListCompanies.Add(company2);
ListCompanies.Add(company3);
var Exp = ListCompanies.Where(e => ListCompanies.Contains(e.Expense));
This doesn't work as I'm getting this error:
Argument 1: cannot convert from 'int' to 'Project1.Company
I know I could get the direct values out of a LINQ query like this:
var CompanyName = ListCompanies.Where(cn => cn.Name.Contains("X"));
which would give me all company names that contains "X". Isn't it possible to get all company names in ListConpanies?
Hope I'm not to unclear.
Thanks!
You can get all salaries into a separate list with a Select:
var allSalaries = ListCompanies.Select(c => c.Salary).ToList();
This produces a list wit {1000, 800, 1400}
If you do not want a list, but wish to iterate over a particular attribute from your list, you can do a Select in a foreach loop:
foreach (var expense in ListCompanies.Select(c => c.Expense)) {
...
}
To get all salaries, try this:
var salaries = ListCompanies.Select(c => c.Salary);
This will get you an IEnumerable. If desired, you can convert it using ToArray(), ToList()etc.
If you want to get all salaries, simply use Select:
var salaries = ListCompanies.Select(e => e.Salary );
Also, you are not right when saying that:
var CompanyName = ListCompanies.Where(cn => cn.Name.Contains("X"));
would give you all company names that contains "X". It will return a IEnumerable<Company> of companies which name contains "X". It might not single but multiple companies. You can then select their salaries by combining Where and Select clauses:
var filteredSalaries = ListCompanies.Where(c => c.Name.Contains("X"))
.Select(c => c.Salary);
You are getting the error because you are searching an int Expense in a collection of (Company type) companies so type difference causes the error.
You can select any property from a IEnumerable by using Select extenion Method and it will return IEnumerable.
var Expenses = ListCompanies.Select(c => c.Expenses);
var Salaries = ListCompanies.Select(c => c.Salary);
var Years = ListCompanies.Select(c => c.Year);
These all Expenses, Salaries and Years are of IEnurable type. If you want list from this then you have to call ToList() extension method.
var Expenses = ListCompanies.Select(c => c.Expenses).ToList();
var Salaries = ListCompanies.Select(c => c.Salary).ToList();
var Years = ListCompanies.Select(c => c.Year).ToList();

Resources