I have the following problem I am creating a form that is a budget replica, but this type of budget does not carry VAT% and good will not pass through accounting.
Well the problem is the following I have created a model called budget.table
It is the following :
class TableElements(models.Model):
_name = 'budget.table'
product_id = fields.Many2one('product.product', string='Product',ondelete='restrict', index=True)
name = fields.Text(string='Description', required=True)
quantity = fields.Float(string='Quantity',required=True, default=1)
price_unit = fields.Float(string='Unit Price', required=True,)
price_subtotal = fields.Float(string='Amount',store=True, readonly=True)
and I have another model called budget.two which is the following:
class BudgetTwo(models.Model):
_name = 'budget.two'
name = fields.Char(string ='Nombre', copy=False, index=True ,default ="Nuevo")
partner_id =fields.Many2one('res.partner' ,string ='Cliente', copy=False, index=True,required=True)
deliver_date = fields.Date(string ='Fecha de Entrega')
expiration_date = fields.Date(string ='Fecha de expiración')
pay_place =fields.Many2one('account.payment.term' ,string='Plazo de Pago')
order_line = fields.One2many('budget.table','id' ,string = 'Pedidos' )
total = fields.Float(string = 'Total:' ,compute="_total")
Well I want: as you can see in 'budget.two' there is a One2Many field which I will add all the new products that in turn will be saved in this type of new budget that I am created as I already commented without VAT and it will not happen by the accounting module.
When I select the products that I am going to save the One2manny, I keep it blank. Example:
So it should be kept:
but when you save it, look how it is stored without any element in the One2MAny field:
[![enter code here][2]][2]
In 'budget.table' add this field:
budget_two_id = fields.Many2one('budget.two')
In 'budget.two' correct this field:
order_line = fields.One2many('budget.table', 'budget_two_id', string='Pedidos')
The point is any One2many field should have an inverse field (Many2one) on the other model as a foreign key.
Related
I am trying to update field price in model custom.sale.line that's related to field product_id.sell_price in model custom.price but without affecting the original value of the latter (in other way i want the cashier to able to change the value on the sales invoice but without changing the value of the product in the database), i'm wondering if there's any change to do so
I tried making another field other_price that takes the value of price, but even with store=True it doesn't save the new value in the database and reverts to the original value
if anyone have a solution for this problem i would be thankful
below is the code
class CustomSaleLine(models.Model):
_name = 'custom.sale.line'
_sql_constraints = [
('product_br_uniq', 'unique(order_id, product_id)',
'Cannot add a product that already exists')]
product_id = fields.Many2one(comodel_name="custom.product", string="Product",
domain="[('branch_line.branch_id.user_lines.user_id','=', user_id)]")
sell_price = fields.Float(string='Main Price', related='product_id.sell_price', required=True, )
other_price = fields.Float(string='Other Price', compute='_compute_price', store=True)
store=True, )
#api.depends('sell_price')
def _compute_price(self):
for rec in self:
rec.other_price = rec.sell_price
Try
sell_price = fields.Float(string='Main Price', inverse='_compute_dummy', compute='_compute_price', required=True, store=True)
#api.depends('product_id.sell_price')
def _compute_price(self):
for rec in self:
rec.sell_price = rec.product_id.sell_price
def _compute_dummy(self):
pass
I am creating a module something like call log. In that i need to search the customer number and get the Partner information or have to link the partner automatically.
the following are the codes, somebody please help me.
class model_call(models.Model):
_inherit = 'res.partner'
_name = 'model.call'
_description = 'call logs'
""" *************** Base Fields ******************* """
name = fields.Char(string='Topic')
customer_number = fields.Char(string='Customer Number', track_visiility='onchange', onchange='get_partner(customer_number)')
#-------------------------------------------------
# apis
#-------------------------------------------------
#api.onchange('customer_number')
def get_partner(self, customer_number):
if customer_number:
customer = self.env['res.partner'].search([('customer_number', '=', record.phone)])
return customer
#------------------------------------------------------
customer = fields.Many2one('res.partner', string='Customer', track_visibility='onchange',index=True, help="Linked partner (optional). Usually created when converting the lead.",)
Your onchange isn't correct. You don't need parameters and have to return a dictionary or nothing. The dictionary is only needed for field filtering changes and warning messages. Value changes like yours are made "directly":
#api.onchange('customer_number')
def get_partner(self):
if self.customer_number:
customer = self.env['res.partner'].search(
[('customer_number', '=', self.phone)]) # shouldn't it be self.customer_number?
self.customer = customer
And try to stick to the Odoo Guidelines and change the field customer to customer_id.
Hello to all I have been developing module under Odoo 8. I have a class "hrEmployee" with "_inherit=hr.employee" , now in my hrEmployee there is a One2many field having relation with another model "hr.employee.visa". I want to get the field values of the "hrEmployee" with onchange function defined on the field of "hr.employee.visa". Like when I change field value of "hrEmployee", I can get the field value entered on the current form (hrEmployee). How am I able to achieve this in Odoo v8? My Python code is shown below:
class hrEmployee(models.Model):
_inherit = "hr.employee"
diwan_no = fields.Char('Diwan No', size=30, help='Diwan Number')
zeo_number = fields.Char('ZEO Number',size=30, help='ZEO Number')
visas_ids = fields.One2many('hr.employee.visas', 'employee_id', 'Visas')
class hr_employee_visas(models.Model):
_name='hr.employee.visas'
employee_id = fields.Many2one("hr.employee.visas", "Employee" )
#api.onchange('visas_number')
#api.depends( 'visas_number')
def _visa_num(self):
cr=self._cr
uid=self._uid
ids=self._ids
for id in ids:
obj1=self.pool.get('hr.employee').browse(cr,uid,id,context=None)
print obj1.name_related
visas_sponsor = fields.Char('Sponsor')
visas_states = fields.Selection([('apply','Apply'),('active','Active'),('expire','Expire'),('cancel','Cancelled')], string='State' )
visas_number = fields.Char('Visa No', help='Visa Number')
I tried to use self.pool.get browse but it gives me "False" . Plz guide me or point me my mistake. Hopes for suggestion
Try following,
class hr_employee_visas(models.Model):
_name='hr.employee.visas'
employee_id = fields.Many2one("hr.employee", "Employee" )
#api.onchange('visas_number')
#api.depends( 'visas_number')
def _visa_num(self):
for obj in self:
print obj.employee_id.name
Here is the mistake
employee_id = fields.Many2one("hr.employee.visas", "Employee" )
You need to set hr.employee here.
No need to write both of the decorators together, in case of any changes into the visas_number field this method will be called, you can use any of the single decorator for this.
I'm a Django beginner and am getting acquainted to using it, and I'm also a big believer in unit testing.
Given a sample database table contracts with the fields
parent_id int
contract_num varchar
start_date date
end_date date
org_name varchar
I defined a model class by using django_admin.py inspectdb > models.py
class Contracts(models.Model):
parent_id = models.IntegerField()
contract_num = models.CharField(max_length=10L, db_column='contract_num')
start_date = models.DateField()
end_date = models.DateField(null=True, blank=True)
org_name = models.CharField(max_length=100L, db_column='org_name')
class Meta:
db_table = 'contracts'
Within the test class, I defined
def setUp(self):
self.contracts = Contracts(parent_id = 300, contract_num = "1234", start_date = timezone.now(), end_date = None, org_name = "TestContractName")
def test_contracts_access(self):
self.contracts.save()
getContracts = Contracts.objects.get(parent_id = 300)
self.assertEqual(getContracts.org_name, "TestContractName")
self.assertEqual(getContracts.contract_num, "1234")
self.assertEquals(getContracts.contract_num, "12")
getContracts.org_name = "TestContractNameUpdate"
getContracts.save()
updateContract = Contracts.objects.get(contract_num = "1234")
self.assertEqual(updateContract.org_name, "TestContractNameUpdate")
When I run this test, I get a database error 1054: "Unknown column contracts.id in field list". What exactly does that mean? The first error in the stack trace is the get call right after the first save.
Thing is, I have an exact same test set up for another model object and that one passes.
Make sure to check the primary key that is set in the database. If you have a primary key that is on a field not labeled "id" (I'm looking at you parent_id...), then you need to set this in your model. You can do this with :
field_name = models.AutoField(primary_key=True)
If you do not do this, then Django will look for the field "id", assuming that you have one and that it is your primary key. I think you are getting this error because it is looking for contracts.id which does not exist!
Check out the Django docs on primary-key-fields and legacy databses.
I'd like to define a set of model/objects which allow for one to represent the relationship: field_set has many fields where fields are django.db.model field objects (IPAddressField, FilePathField etc).
My goals is to have a ORM model which supports the following type of 'api'.
From a controller view lets say:
# Desired api below
def homepage(request):
from mymodels.models import ProfileGroup, FieldSet, Field
group = ProfileGroup()
group.name = 'Profile Information'
group.save()
geographicFieldSet = FieldSet()
# Bind this 'field set' to the 'profile group'
geographicFieldSet.profilegroup = group
address_field = Field()
address_field.name = 'Street Address'
address_field.f = models.CharField(max_length=100)
# Bind this field to the geo field set
address_field.fieldset = geographicFieldSet
town_field = Field()
town_field.name = 'Town / City'
town_field.f = models.CharField(max_length=100)
# Bind this field to the geo field set
town_field.fieldset = geographicFieldSet
demographicFieldSet = FieldSet()
demographicFieldSet.profilegroup = group
age_field = Field()
age_field.name = 'Age'
age_field.f = models.IntegerField()
# Bind this field to the demo field set
age_field.fieldset = demographicFieldSet
# Define a 'weight_field' here similar to 'age' above.
for obj in [geographicFieldSet, town_field, address_field,
demographicFieldSet, age_field, weight_field]:
obj.save()
# Id also add some methods to these model objects so that they
# know how to render themselves on the page...
return render_to_response('page.templ', {'profile_group':group})
Essentially I want to support 'logically grouped fields' since I see myself supporting many 'field sets' of different types thus my desire for a meaningful abstraction.
Id like to define this model so that I can define a group of fields where the # of fields is arbitrary as is the field type. So I may have a field group 'Geographic' which includes the fields 'State' (CharField w/ choices), 'Town' (TextField) etc.
Heres what Ive come up with so far:
class ProfileGroup(models.Model):
name = models.CharField(max_length=200)
# FieldSets have many Fields
class FieldSet(models.Model):
name = models.CharField(max_length=200)
profilegroup = models.ForeignKey(ProfileGroup)
class Field(models.Model):
f = models.Field()
fieldset = models.ForeignKey(FieldSet)
Though using these models produces an error in the shell and ultimately doesnt allow me to store arbitrary fields.
In [1]: from splink.profile_accumulator.models import Field, FieldSet, ProfileGroup
In [2]: import django.db
In [3]: profile_group = ProfileGroup()
In [4]: profile_group.name = 'profile group name'
In [5]: profile_group.save()
In [6]: field_set = FieldSet()
In [7]: field_set.name = 'field set name'
In [8]: field_set.profilegroup = profile_group
In [9]: field_set.save()
In [10]: field = Field()
In [11]: field.name = 'field name'
In [12]: field.f = django.db.models.FileField()
In [13]: field.save()
---------------------------------------------------------------------------
ProgrammingError Traceback (most recent call last)
/var/www/splinkpage.com/splinkpage.pinax/splink/<ipython console> in <module>()
/usr/lib/pymodules/python2.5/django/db/models/base.pyc in save(self, force_insert, force_update)
309 raise ValueError("Cannot force both insert and updating in "
310 "model saving.")
--> 311 self.save_base(force_insert=force_insert, force_update=force_update)
312
313 save.alters_data = True
/usr/lib/pymodules/python2.5/django/db/models/base.pyc in save_base(self, raw, cls, force_insert, force_update)
381 if values:
382 # Create a new record.
--> 383 result = manager._insert(values, return_id=update_pk)
384 else:
385 # Create a new record with defaults for everything.
/usr/lib/pymodules/python2.5/django/db/models/manager.pyc in _insert(self, values, **kwargs)
136
137 def _insert(self, values, **kwargs):
--> 138 return insert_query(self.model, values, **kwargs)
139
140 def _update(self, values, **kwargs):
/usr/lib/pymodules/python2.5/django/db/models/query.pyc in insert_query(model, values, return_id, raw_values)
890 part of the public API.
891 """
892 query = sql.InsertQuery(model, connection)
893 query.insert_values(values, raw_values)
--> 894 return query.execute_sql(return_id)
/usr/lib/pymodules/python2.5/django/db/models/sql/subqueries.pyc in execute_sql(self, return_id)
307
308 def execute_sql(self, return_id=False):
--> 309 cursor = super(InsertQuery, self).execute_sql(None)
310 if return_id:
311 return self.connection.ops.last_insert_id(cursor,
/usr/lib/pymodules/python2.5/django/db/models/sql/query.pyc in execute_sql(self, result_type)
1732
1733 cursor = self.connection.cursor()
-> 1734 cursor.execute(sql, params)
1735
1736 if not result_type:
/usr/lib/pymodules/python2.5/django/db/backends/util.pyc in execute(self, sql, params)
17 start = time()
18 try:
---> 19 return self.cursor.execute(sql, params)
20 finally:
21 stop = time()
ProgrammingError: can't adapt
So Im wondering if this is totally the wrong approach or if I need to use django's model classes a bit differently to get what I want.
I see several problems with the code. First, with this class definition:
class Field(models.Model):
f = models.Field()
fieldset = models.ForeignKey(FieldSet)
The class models.Field is not supposed to be used directly for a field definition. It is a base class for all field types in Django so it lack specifics for a particular field type to be useful.
The second problem is with the following line:
In [12]: field.f = django.db.models.FileField()
When you assign to attribute f of your Field instance, you are supposed to give a specific value to be saved to the database. For example, if you used CharField for Field.f definition, you would assign a string here. models.Field has no specific assignable values though. You are trying to assign something that is clearly not possible to save to the DB. It is modles.FileField definition.
So, Django has a hard time to "adjust" the value you are assigning to the field attribute for two reasons. First, the are no values defined for models.Field type to assign as it is an "abstract class", or a base class for specific field type definitions. Second, you can not assign "field definition" to an attribute and hope that it is going to be saved to a DB.
I understand your confusion. You are basically trying to do impossible thing both from the DB and Django's points of view.
I suppose there could be a solution for your design problem though. If you describe what you are trying to achieve in detail, somebody could probably give you a hint.
In SQL there is no such thing as a table with variable number of columns or variable type columns. Also, Django does not modify database layout at run time - i.e. does not call ALTER TABLE statements - as far as I know.
In django data models must be completely defined before you run your application.
You might find this doc page relevant for use of "many-to-one" relationships.
Example:
#profile
class ProfileGroup(models.Model):
...
#fieldset
class FieldSet(models.Model):
profile = models.ForeignKey(ProfileGroup)
#field 1
class Address(models.Model)
owner = models.ForeignKey(FieldSet,related_name='address')
#related name above adds accessor function address_set to Profile
#more fields like street address, zip code, etc
#field 2
class Interest(models.Model)
owner = models.ForeignKey(FieldSet,related_name='interest')
description = models.CharField()
#etc.
Populate and access fields:
f = FieldSet()
f.interest_set.create(description='ping pong')
f.address_set.create(street='... ', zip='... ')
f.save()
addresses = f.address_set.all()
interests = f.interest_set.all()
#there are other methods to work with sets
sets in this case emulate variable fields in a table Profile. In the database, however, interest and address data is stored in separate tables, with foreign key links to Profile.
If you want to access all that with one accessor function - you could write something that wraps calls to all related sets.
Even though you can't modify model on the fly, you can add new models then issue
manage.py syncdb
This will create new tables in the db. However you won't be able to modify fields in existing tables with 'syncdb' - django doesn't do it. You'll have to enter SQL commands manually for that. (supposedly web2py platform handles this automatically, but unfortunately web2py is not well documented yet, but it might be a cut above django in terms of quality of API and is worth taking a look at)
Why not to make sth like this?
class Info(models.Model):
info_type = models.ForeignKey('InfoType', blank=False, null=False, default='')
info_int = models.IntegerField(null=True, blank=True)
info_img = models.ImageField(upload_to='info',null=True, blank=True)
info_date = models.DateTimeField(null=True, blank=True)
info_text = models.TextField(null=True, blank=True)
info_bool = models.BooleanField(null=True, blank=True)
info_char = models.CharField(max_length=128,null=True, blank=True)
info_dec = models.DecimalField(max_digits=20, decimal_places=12, null=True, blank=True)
info_float = models.FloatField(null=True, blank=True)
parent_info = models.ForeignKey('self', blank=True, null=True)
class InfoType(models.Model):
type = models.CharField(max_length=64, blank=False, null=False, default='')
info_field = models.CharField(max_length=32, blank=False, null=False, default='')
so depending which type we choose we know in which field we can find the value