Get value from the ListView - odoo-8

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)

Related

I have to filter data in Many2one field

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

How to get item name instead of item id in django restframework (foreignkey case)

I am trying to get itemwise inventory desired result is like this
[
{
'item' : shoes,
'total_unit' : 134
},
{
'item': sneaker,
'unit': 100
}
]
but I am getting result like
[
{
"item": 5,
"unit": 134
},
{
"item": 4,
"unit": 100
}
]
I want to get item name instead of id
Models.py
class Item(models.Model):
item_name = models.CharField(max_length=50)
srn_code = models.CharField(max_length=20,unique=True)
category = models.ForeignKey(Category,related_name='categories',on_delete=models.CASCADE)
def __str__(self):
return self.item_name
class Transaction(models.Model):
category = models.ForeignKey(Category,on_delete=models.CASCADE)
item = models.ForeignKey(Item,on_delete=models.CASCADE)
size = models.CharField(blank=True,max_length=20)
unit = models.IntegerField()
unit_price = models.DecimalField(decimal_places=2,max_digits=20)
supplier = models.ForeignKey(Supplier,on_delete=models.CASCADE)
tran_date = models.DateField(auto_now=False,auto_created=False,blank=False)
created_date = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.item.item_name} {self.unit}"
serializer.py
class InventorySerializer(serializers.ModelSerializer):
item = serializers.CharField(read_only=True)
total_unit = serializers.IntegerField(read_only=True)
class Meta():
model = Transaction
fields = ['item','total_unit']
views.py
class InventoryModelViewSet(ModelViewSet):
queryset = Transaction.objects.all()
serializer_class = InventorySerializer
def get_queryset(self):
return Transaction.objects.values('item').annotate(
total_unit = Sum('unit')
).order_by('item')
Thanks for posting my question, I have sorted out my question, my solution is below, if anybody needs or gets query like this, then its might be helpful.
I have declared a method in serializers class for get item_name from another table
class InventorySerializer(serializers.ModelSerializer):
item = serializers.CharField(read_only=True)
total_unit = serializers.IntegerField(read_only=True)
item_name = serializers.SerializerMethodField()
class Meta():
model = Transaction
fields = ['item','item_name','total_unit']
def get_item_name(self, obj):
item_obj = Item.objects.filter(id=obj['item']).first()
item_name = model_to_dict(item_obj)
return item_name['item_name']
`

Django GraphQL Mutation Updated, but no change in Database

I created an update mutation as follows, with django==3.1.4 and graphene==2.1.8 :
# models.py
class CustomUser(AbstractUser):
# email = models.EmailField()
firebase_id = models.CharField(max_length=50, null=True)
nickname = models.CharField(max_length=50, null=True)
name = models.CharField(max_length=20, null=True)
gender = models.IntegerField(choices=Gender, default=3)
phone = models.CharField(max_length=20, null=True)
birthday = models.DateField(default=datetime(2020,1,1))
address = models.CharField(max_length=200, null=True)
profile_image = models.ImageField(default='default-avatar.png', upload_to='users/',
null=True, blank=True)
class UpdateMember(graphene.Mutation):
class Arguments:
firebase_id = graphene.String(required=True)
nickname = graphene.String()
name = graphene.String()
gender = graphene.Int()
phone = graphene.String()
birthday = graphene.Date()
address = graphene.String()
profile_image = graphene.String()
class Meta:
exclude = ["password"]
member = graphene.Field(MemberType)
success = graphene.Boolean()
# #login_required
#staticmethod
def mutate(root, info, firebase_id, **kwargs):
success = False
member_instance = CustomUser.objects.get(firebase_id=firebase_id)
if member_instance:
print(member_instance)
success = True
for k, v in kwargs.items():
member_instance.k = v
member_instance.save()
return UpdateMember(member=member_instance, success=True)
else:
return UpdateMember(member=None, success=False)
Running GQL below:
mutation {
updateMember(
firebaseId:"777",
name:"JJJJ")
{
success
}
}
Response:
{
"data": {
"updateMember": {
"success": true
}
}
}
But I checked the database, it seems no change in it, I think .save() should have done the work persisting changes to database......
Creating Member works fine. Using PostgresQL
Could anyone figure out why?
There is several issues in your code:
You can not assign your model fields using string like that. See this thread
for k, v in kwargs.items():
member_instance.k = v
member_instance.save()
Currently your member_instance.k has nothing to do with variable k inside for loop.
firebase_id field should be unique.
Currently you call CustomUser.objects.get(firebase_id=firebase_id) which is risky because firebase_id is not unique field. This may lead Multiple objects error if you have more than one CustomUsers saved with same id. To fix it, just define:
class CustomUser(AbstractUser):
# email = models.EmailField()
firebase_id = models.CharField(max_length=50, unique=True)
...
To check if your member_instance has really updated. You can for example print out the values before saving it and run some test cases before final implementation. For example:
if member_instance:
print(member_instance)
success = True
for k, v in kwargs.items():
member_instance.k = v
print(member_instance.k)
print(k)
print(getattr(member_instance, k))
member_instance.save()

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!')]

Convert Suport Ticket to TASK Odoo 9

Is it possible convert Suport Ticket to Project > Task.
Task Title = Suport subject, Task Description = Suport Description...
Example:
I use this modul https://www.odoo.com/apps/modules/9.0/website_support/
In support ticket i want add:
Below is new function def generate_task(self): how generate new TASK from that.
class WebsiteSupportTicketCompose(models.Model):
_name = "website.support.ticket.compose"
ticket_id = fields.Many2one('website.support.ticket', string='Ticket ID')
partner_id = fields.Many2one('res.partner', string="Partner", readonly="True")
email = fields.Char(string="Email", readonly="True")
subject = fields.Char(string="Subject", readonly="True")
body = fields.Html(string="Message Body")
template_id = fields.Many2one('mail.template', string="Mail Template", domain="[('model_id','=','website.support.ticket')]")
#api.onchange('template_id')
def _onchange_template_id(self):
if self.template_id:
values = self.env['mail.compose.message'].generate_email_for_composer(self.template_id.id, [self.ticket_id.id])[self.ticket_id.id]
self.body = values['body']
#api.one
def send_reply(self):
#Send email
values = {}
email_wrapper = self.env['ir.model.data'].get_object('website_support','support_ticket_reply_wrapper')
values = email_wrapper.generate_email([self.id])[self.id]
values['model'] = "website.support.ticket"
values['res_id'] = self.ticket_id.id
send_mail = self.env['mail.mail'].create(values)
send_mail.send()
#(Depreciated) Add to message history field for back compatablity
self.env['website.support.ticket.message'].create({'ticket_id': self.ticket_id.id, 'content':self.body.replace("<p>","").replace("</p>","")})
#Post in message history
#self.ticket_id.message_post(body=self.body, subject=self.subject, message_type='comment', subtype='mt_comment')
staff_replied = self.env['ir.model.data'].get_object('website_support','website_ticket_state_staff_replied')
self.ticket_id.state = staff_replied.id
#api.one
def generate_task(self):
values = {}
print(self.ticket_id.id)
print(self.email)
print(self.subject)
print(self.body.replace("<p>","").replace("</p>",""))
#How this data insert in new TASK
Any simple solution?
Try below code:
#api.multi
def generate_task(self,cr, uid, ids, context=None):
Task = self.pool["project.task"]
vals = {
"name": "TEST",
"description": "DESCRIPTION",
}
task_id = Task.create(cr,uid,vals,context=None)
task = Task.browse(cr,uid,task_id,context=None)

Resources