How to add a filter to selection field in odoo - odoo-9

I need to add a filter to a selection field in odoo..
roomuser = fields.Selection([('stpi', 'Belongs to Park'),('Incubation', 'Belongs to Incubation companies'),('both', 'Belongs to Park& Incubation companies')],'Room Assignment',required=True)
roomType = fields.Selection([('meeting','Meeting Room'),('discussion','Discussion Room'),('auditorium','Auditorium'),('board','Board Room')],required=True)
Here i need to filter the value of roomType based on the value of roomuser. Suppose roomuser value is both only auditorium and board should be visible in roomType

I have made my comments as below , kindly request you to find it as below it may help in your case:
class HotelManagement(models.Model):
_name='hotel.management'
#api.model
def _get_room_type_list(self):
# [('meeting','Meeting Room'),('discussion','Discussion Room'),('auditorium','Auditorium'),('board','Board Room')]
vals=[]
for record in self.env['hotel.management'].search([]):
if record.roomuser in ['stpi','Incubation'] :
vals.extend([('meeting','Meeting Room'),('discussion','Discussion Room')])
if record.roomuser in ['both'] :
vals.extend([('auditorium','Auditorium'),('board','Board Room')])
return vals
def _get_roomuser_list(self):
return [('stpi', 'Belongs to Park'),
('Incubation', 'Belongs to Incubation companies'),
('both', 'Belongs to Park& Incubation companies')]
roomType=fields.Selection(string="Room Type", selection=_get_room_type_list, default='meeting', required=True)
roomuser = fields.Selection(string="Room Assignment",selection=_get_roomuser_list ,required=True)
Here i have just put #api.model on top _get_room_type_list and traversing all the record in this(hotel.management) model and filtering the selection field .

Related

Increasing the count field of model whenever a search is applied

I have a search api
class SearchViewSet(RetrieveModelViewSet):
serializer_class = ArticleSerializer
queryset = Article.objects.all()
query = self.request.query_params.get("query")
final_queryset = search(query,queryset,#some logic)
#logic to generate serialiser and return serialiser.data
serialiser = self.get_serializer(final_ueryset, many=True)
search function returns a list of articles i.e
type(final_queryset) is List
And. I wan't to return the articles order_by('count) as well.
Now I wan't to increase the count of top 3 articles from the final_queryset is there a way of doing this.
Add created_at field in your model, then use this field to find top 3 item or latest 3 items like this, and then increase count
queryset = Article.objects.order_by('-created_at')[:3] # it will return a queryset of latest 3 items
for article in queryset:
article.count += 1
article.save()
serializer = ArticleSerializer(article)
Note: I only shared the logic part here, and i can't test it in my local, but it should work and help you to get the idea. Use it on your need.
Figured out a way for doing this
Just simply iterate on the list and increment the count of the objects in the list
class SearchViewSet(RetrieveModelViewSet):
serializer_class = ArticleSerializer
queryset = Article.objects.all()
query = self.request.query_params.get("query")
final_queryset = search(query,queryset,#some logic)
# to increment the count of top 3 entity_aliases
for instance in final_queryset[:3]:
instance.count += 1
instance.save()
#logic to generate serialiser and return serialiser.data
serialiser = self.get_serializer(final_ueryset, many=True)

queryset filter between 2 values whit foreing keys?

I have problems with the following queryset, I probe it in django shell and it returns an empty list.
The situation is that I'm occupying a lforeing key, I did the same exercise with the model "Tarifa_Sem" and returns the value without any problem, just replace the F ('') by a variable x = 1000
The situation is that the table of the model "Tarifa_Sem" is only for consultation.
Where I am going to manage and save the response of the queryset is in the "Calculadora_isr" model
Model 1
class Tarifa_Sem(models.Model):
limite_inferior_isr = models.DecimalField(max_digits=10, decimal_places=2)
limite_inferior_subsidio = models.DecimalField(max_digits=10, decimal_places=2)
limite_superior = models.DecimalField(max_digits=10, decimal_places=2)
Model 2
class Calculadora_isr(models.Model):
tarifa = models.ForeignKey(Tarifa_Sem, on_delete=models.CASCADE, blank=True)
base_gravada = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
limite_inf_calculo = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
Queryset and save()
def limite_inferior(self):
queryset = Calculadora_isr.objects.filter(tarifa__limite_superior__gte=F('base_gravada'),tarifa__limite_inferior_isr__lte=F('base_gravada')).distinct().values('tarifa__limite_inferior_isr')
return queryset
def save(self):
self.limite_inf_calculo = self.limite_inferior
super (Calculadora_isr, self).save()
In the shell of django the list appears empty.
>>> queryset = Calculadora_isr.objects.filter(tarifa__limite_superior__gte=F('base_gravada'),tarifa__limite_inferior_isr__lte=F('base_gravada')).distinct().values('tarifa__limite_inferior_isr')
And in the admin when I give him save he tells me:
conversion from method to Decimal is not supported
thanks for the support
I finally found the solution.
To solve the problem of passing the "base_gravada" field, use another variable that returns all the values ​​of "base_gravada"
qs1 = Calculadora_isr.objects.values_list('base_gravada')
And in my second query, use the variable qs1:
qs2 = Tarifa_Sem.objects.filter(limite_superior__gte=qs1,limite_inferior_isr__lte=qs1).distinct().values('limite_inferior_isr')

one2many field get row number

I have a module contain one2many filed.
while I create data line in this o2m field, I'd like to append a row number to it.
I have try some method that I found in forum, like this link.
but since I have no function called _onchange_partner_id() , I don't know how to use it.
or this link .
but it seems like an old version method that I can't get well.
class YcWeight(models.Model):
_name = "yc.weight"
customer_detail_ids = fields.One2many("yc.weight.details", "name", "customer details")
class YcWeightDetails(models.Model):
_name = "yc.weight.details"
name = fields.Many2one("yc.weight", "weight detail list", ondelete="cascade")
no = fields.Integer("row number")
the "no" is a field that I want to show number of row count.
my problem is :
how can I get get the number of rows?
since onchage decorated function can't get data from db.
I find a solution by myself and it is simple:
use depends decorator.
class YcWeightDetails(models.Model):
_name = "yc.weight.details"
name = fields.Many2one("yc.weight", "weight detail list", ondelete="cascade")
no = fields.Integer("row number")
compuute_no = fields.Integer("invisible field", compute= "_get_row_no")
create a field "compuute_no" to compute.
#api.depends("compuute_no")
def _get_row_no(self):
if self.ids:
count =1
for rec in self:
weight_id = self.env['yc.weight.details'].search([('id','=', rec.id)])
weight_id.write({'no': count})
count+=1
or overwrite create method
#api.model
def create(self, vals):
main_key = self.env["yc.weight"].search([], order="id desc", limit=1).id
item_key = vals["name"]
if item_key and main_key == item_key:
number = len(self.env["yc.weight.details"].search([("name", "=", item_key)]))
vals.update({"no": number + 1})
return super(YcWeightDetails, self).create(vals)
hope it can help you.

How can I create a complete_name field in a custom module for a custom hierarchy like used on product categories in Odoo?

I'm trying to create a field “complete_name” that displays a hierarchy name similar to whats done on the product categories grid but I can't seem to get it to work. It just puts Odoo in an endless loading screen when I access the relevant view using the new field "complete_name".
I have tried to copy the code used in addons/product/product.py and migrate to work with Odoo 9 API by using compute instead of .function type but it did not work.
Can someone help me understand whats wrong? Below is my model class which works fine without the complete_name field in my view.
class cb_public_catalog_category( models.Model ):
_name = "cb.public.catalog.category"
_parent_store = True
parent_left = newFields.Integer( index = True )
parent_right = newFields.Integer( index = True )
name = newFields.Char( string = 'Category Name' )
child_id = newFields.One2many( 'catalog.category', 'parent_id', string = 'Child Categories' )
complete_name = newFields.Char( compute = '_name_get_fnc', string = 'Name' )
def _name_get_fnc( self ):
res = self.name_get( self )
return dict( res )
Your compute function is supposed to define the value of an attribute of your class, not return a value. Ensure the value you are assigning complete_name is a string.
Also name_get() returns a tuple. I am not sure if you really want a string representation of this tuple or just the actual name value.
Try this
def _name_get_fnc( self ):
self.complete_name = self.name_get()[1]
If you really want what is returned by name_get() then try this.
def _name_get_fnc( self ):
self.complete_name = str(self.name_get())
If you are still having issues I would incorporate some logging to get a better idea of what you are setting the value of complete_name to.
import logging
_logger = logging.getLogger(__name__)
def _name_get_fnc( self ):
_logger.info("COMPUTING COMPLETE NAME")
_logger.info("COMPLETE NAME: " + str(self.name_get()))
self.complete_name = self.name_get()
If this does not make it apparent what the issue is you could always try statically assigning it a value in the off chance that there is a problem with your view.
def _name_get_fnc( self ):
self.complete_name = "TEST COMPLETE NAME"
After further review I think I have the answer to my own question. It turns out as with a lot of things its very simple.
Simply use "_inherit" and inherit the product.category
model. This gives access to all the functions and fields
of product.category including the complete_name field
and computes the name from my custom model data. I was
able to remove my _name_get_func and just use the inherited
function.
The final model definition is below. Once this
update was complete I was able to add a "complete_name" field
to my view and the results were as desired!
class cb_public_catalog_category( models.Model ):
_name = "cb.public.catalog.category"
_inherit = 'product.category'
_parent_store = True
parent_left = newFields.Integer( index = True )
parent_right = newFields.Integer( index = True )
name = newFields.Char( string = 'Category Name' )
child_id = newFields.One2many( 'catalog.category', 'parent_id', string = 'Child Categories' )

Django rest framework serialize queryset of many models

I would like to combine 2 querysets from 2 differents models, then I need to order them by date and finally my goal is to serialize it.
So far I did that :
last_actions = serializers.SerializerMethodField()
def get_last_actions(self, obj):
prc = obj.product_request_configs.all().order_by('modified_date')[:5]
psc = obj.product_send_configs.all().order_by('modified_date')[:5]
result_list = sorted(
chain(prc, psc),
key=attrgetter('modified_date'),
reverse=True)
But I don't know how to call my two django rest serializers so that I can return the right data.
If I could make a database view it coult be simpler I think.
Serializers are designed for match one model relationship, so we need to create a custom Model for the logic you are trying to achieve:
class CustomModel(models.Model):
def dictfetchall(self, cursor):
"""Returns all rows from a cursor as a dict"""
desc = cursor.description
return [dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()]
def yourMethod(self):
cursor = connection.cursor()
cursor.execute("""
select field1, field2 from app_table
where field1=%s and field2=%s group by field1
""",
[value1, value2,]
)
return self.dictfetchall(cursor)
class Meta:
abstract = True
This will return a dictionary and then you can serialize that response with a seializer like:
class CustomModelSerializer(serializers.Serializer):
field1 = serializers.IntegerField()
field2 = serializers.CharField()
Please note that on SQL you can use as keyword to rename some fields, the current name of fields must match var names in your serializer.

Resources