Co dependent fields in Odoo 9.0 view - odoo

Hello everybody and thanks for taking the time to read my question:
I need to make two fields update on each other changes in my view, let's say one of them list's ingredients and the other lists food requirements
requirements = fields.Selection([(0,"Vegan"),(1,"Lactose intolerant")])
ingredients_id = fields.Many2Many(comodel_name="sample.ingredients")
What i need is to update ingredients_id's domain to show only those who match a requirement and vice versa, if you happend to select and ingredient the other field selecting the proper requirement. I'm thinking about making field A a computed field depending on fieldB and then add an on_change to field B that updates field A. But I'm pretty certain that will turn into some kind of infinite loop situation. Is that my only option or am I missing something obviuos?

Use #api.depends decorator and pass both fields as parameters in the decorator. This will trigger function every time on change on both values and will be dependent on each other.
#api.depends('requirements','ingredients_id')
def function (self): ....
do something....
return

Related

Compute many2many field with values from another model using Odoo developer interface

I need a new field inside Contact model that would hold information about Allowed companies of the related user.
Now there is only field about Currently picked company by that user (and it is not enough for me to make a record rule).
The field I want to copy values from is inside model Users and it is called company_ids.
I’m trying to add this field in the developer mode (Settings > Technical > Fields) like this:
But I’m having trouble with code that would fill my field with values from the another model.
for record in self:
record[("x_company_ids")] = env['res.users'].company_ids
I’m guessing that the record is referring to a record inside Contact model and it does not contain fields from another models like Users. So I can’t figure it out how to reference a field from another model.
Something similar to this: env['res.users'].company_ids?
It is even harder for me because it is many2many field and should always update when the source changes.
Maybe better solution would be to use Automatic action to write values to this field?
I saw some threads like this: Computed many2many field dependencies in Odoo 10.
But it seems like in those cases they had clear connection between the fields and I don't have it. I don't know how to get related user while I'm inside Contact model. I know only how to this oposite way (from user to contact): user.partner_id.id
Here in below given code you haven't specified related user from which you will get company_ids, you have directly accessing company_ids
for record in self:
record[("x_company_ids")] = env['res.users'].company_ids
You can write as following :
for record in self:
record["x_company_ids"] = self.env['res.users'].search([('partner_id','=',record.id)]).company_ids

How to create a temp boolean field with Django orm

Image I have following models:
class Product(models.Model):
name = models.CharField(max_length=20)
class Receipt(models.Model):
product = models.ForeignKey(Product)
user = models.ForeignKey(User)
I have an input list of product ids and a user. I want to query for each product, whether it's been purchased by this user. Notice I need a queryset with all exist products based on given input because there are other fields I need for each product even not purchased by this user, so I cannot use Product.objects.filter(receipt__user=user).
So can I create a temp Boolean field to present this property in one single query? I am using Django 1.8 and postgresql 9.3
Update requirements:To separate products into two groups. One is bought by this specific user, the other one is not. I don't think any given filter can implement this. This should be implement by creating a new temp field either by annotate or F expression.
I think, you need .annotate() expression as
from django.db.models.expressions import Case, When, Value
product_queryset = Product.objects.annotate(
is_purchased=Case(
When(receipt__user=current_user, then=Value('True')),
default=Value('False')
))
How to access the annotated field?
product_queryset.first().is_purchased
Thx for #JPG's answer.
I just realize except conditional expressions, there's another easy way to do it.
Just using prefetch_related will implement everything in two queries. Although it's double than conditional expressions, but it's still a considerable time complexity solution.
products = Product.objects.filter(id__in=[1,2,3,4,5]).prefetch_related ('receipt_set').all()
Then we can detect user for this product in Python by
for p in products:
print user in [receipt.user_id for receipt in p.purchase_set.all()]

database design in django for 2-rows multiple colums

I am trying to create a model for the following data in django.
I have around 20 columns and they can increase with time but I will only have one row for the values of each column which will update with time. What would be the best way of creating a model for such a data? I cannot transpose the rows into columns because the data is coming from another source which needs the database in the above format.
you can define a model say TheModel (a relevent name, may be). and each column would be one attribute. This way you can add more attributes as the column increases.
According to your description, This model will have only one object. but that is fine right.
class TheModel(models.Model):
mda_table_ndx = models.CharField(max_length=200)
mf_p030_.._.._.. = models.IntegerField()
..............
.............
Let us know if there is a downside to this.

Ms Access SQL Limit control by previous field value

In a recipe database I have two tables. One has the ingredients of every recipe [Recipe_ingr] and the other the available measures and weight for every ingredient [Weight2].
When I input a new ingredient for a recipe, I would like to be able to choose the available units for only that specific food.
I have tried with this expression in the control field but it prompts me to choose first, and then the options remain the same for all the records, not changing dinamically according to the record ingredient code.
SELECT [Weight2].[Msre_Desc], [Weight2].[Gm_Wgt] FROM Weight2 WHERE Weight2.NDB_No Like Recipe_Ingr.NDB_No ORDER BY [Msre_Desc], [Gm_Wgt];
Picture of my tables
Update:
I tried the syntax change suggested by June9 but still the control doesn't update automatically with every record as you can see in this picture: Table
Suggest you name controls different from fields they are bound to, like tbxNDB. The SQL needs to reference a field or control that is on the form. Also, LIKE operator without wildcard accomplishes nothing that an = sign wouldn't. Also recommend not using exactly same name for fields in multiple tables.
If you use that SQL statement in combobox RowSource, try:
SELECT Msre_Desc, Gm_Wgt FROM Weight2 WHERE NDB_No = [tbxNDB] ORDER BY Msre_Desc, Gm_Wgt;
You want to save Msre_Desc as foreign key, not a record id generated by autonumber?

Few questions about Grails' createCriteria

I read about createCriteria, and kind of interested on how these works, and its usability in providing values for dropdown box.
So say, i have a table in the database, Resource table, where i have defined the table in the domain class called Resource.groovy. Resource table has a total of 10 columns, where 5 of it are
Material Id
Material description
Resource
Resource Id
Product Code
So using the createCriteria, and i can use just like a query to return the items that i want to
def resList = Resource.createCriteria().list {
and {
eq('resource', resourceInstance)
ne('materialId', '-')
}
}
Where in the above, i want to get the data that matches the resource = resourceInstance, and none of the materialId is equal to '-'.
I want to use the returned data from createCriteria above on my form, where i want to use some of the column on my select dropdown. Below is the code i used for my select dropdown.
<g:select id="resourceId" name="resourceId"
from="${resList}"
disabled="${actionName != 'show' ? false : true}" />
How do i make it so that in a dropdown, it only shows the values taken from column Product Code? I believe the list created using createCriteria returns all 10 columns based on the createCriteria's specification. But i only want to use the Product Column values on my dropdown.
How do i customize the data if in one of the select dropdown in my form, i wanted to show the values as "Resource Id - Resource Description"? The values are combination of more than 1 columns for one select dropdown but i don't know how to combine both in a single select dropdown.
I read that hql and GORM query are better ways of fetching data from table than using createCriteria. Is this true?
Thanks
First of all refer to the document for using select in Grails. To answer all questions:
Yes, the list to select from in the dropdown can be customized. In this case it should be something like from="${resList*.productCode}"
Yes, this can be customized as well with something like
from="${resList.collect { \"${it.resourceId} - ${it.resourceDesc}\" } }"
It depends. If there are associations involved in a domain then using Criteria will lead to eager fetches which might not be required. But with HQL one gets the flexibility of tailoring the query as needed. With latest version of Grails those boundries are minimized a lot. Usage of DetachedCriteria, where queries etc are recommended whereever possible. So it is kind of mixing and matching to the scenario under consideration.