Associate a product to a record in own custom module - odoo-12

I'm new to odoo , i want to create a new product in the product module when a new record is created in my own custom module! how can i achieve this goal !?
by the way i'm using odoo v12

Override create method of your custom model and created product in it.
#api.model
def create(self, vals):
res = super(YouClassName, self).create(vals)
self.env['product.product'].create({'name': 'Product1'})
return res

Here is my create function :
#api.model
def create(self, vals):
res = super(GroupsalesGroupsales, self).create(vals)
main_category = self.env['product.category'].search([])
if main_category:
main_category = main_category[0]
self.env['product.template'].create({'name': vals['name'],
'categ_id': main_category.id,
'list_price':vals['prix_rabais'],
'default_code': 'GS-PROD',
'image_small' : vals['image_small'], })
return res

When i try to add _inherits: {'product.product': 'product_id'}
i get this error:
'ERROR:null value in column "name" violates not-null constraint'

Related

How to copy one2many filed in odoo?

I have problem with copy one2many field. I create assignment field for Project:
assignment_ids = fields.One2many(
string='Project Assignments',
comodel_name='project.assignment',
inverse_name='project_id',
track_visibility='onchange',)
First I try to add attribute copy=True and then it throws an error
Error while validating constraint
Expected singleton: project.assignment(3, 4)
And this has the same singleton error
#api.multi
def copy(self, default=None):
default = default or {}
for rec in self:
list_assignment = self.assignment_ids
new_assignment = []
for assignment in list_assignment:
new_assignment.append((0, 0, {'id': assignment.id,
'role_id': assignment.role_id.id,
'date_join': date.today(),
'user_id': assignment.user_id.id,
}))
default['assignment_ids'] = new_assignment
return super(ProjectProject, self).copy(default)
Then I try to override the copy function. The assignment have a copy to new Project but old Project's assignment has been deleted.
#api.multi
def copy(self, default=None):
default = default or {}
list_assignment = self.assignment_ids
default['assignment_ids'] = (6, True, list_assignment)
return super(ProjectProject, self).copy(default)
So how can I copy this one2many field?
Thank you so much!!!
This code works when I copied one2many from sale to one2many field in invoice.
def _prepare_invoice(self):
self.ensure_one()
res=return super([Your_Class_Name], self)._prepare_invoice()
# Loop in your One2many field in sale order
one2many_vals =[]
for l in self.order_id.[Your_One2many]:
one2many_vals.append(
(0,0,{'One2many_column1_in_invoice_One2Many':l.[One2many_column1_in_sale_One2Many],
'One2many_column2_in_invoice_One2Many':l.[One2many_column2_in_sale_One2Many],
'One2many_column3_in_invoice_One2Many':l.[One2many_column3_in_sale_One2Many]
}))
res['One2many_field_name_in_invoice'] = one2many_vals
return res

Creating view for update table via foregien key access in django

I am really new to django and stuck in using foreign key in django queries.Can anyone help me.
Situation:I created a sign up page with username and email field.So when a new user registered, its username and email address saved to auth_user table.
Q: I want to create a model instance in class UserDetails each time a new user register. or you can say entry of user as a foregien key in table userdetails. I am using postgresql database.
Myapp/models.py
class Pincode(models.Model):
pincode = models.CharField("PinCode",null=False)
geom = GeopositionField("Location")
objects = models.GeoManager()
def __unicode__(self):
return u'%s' %(self.pincode)
class UserDetails(models.Model):
user = models.OneToOneField(User, related_name='User_Details',unique=True)
pin= models.ForeignKey(Pincode,related_name='pin', null= True, blank=True)
rating= models.CharField(max_length=12, null=True, blank=True)
def __unicode__(self):
return u'%s, %s, %s' % (self.user, self.pin, self.rating)
views.py
def index(request):
update_user_details()
return render_to_response("larb/index.html",
RequestContext(request))
def update_user_details(request): ## **Stuck here**
user_details = UserDetails.objects.all()
new_entry= User.objects.exclude() # Don't know how to do
currently i am thinking of creating a function in the views that update the table.
first it checks for new entries means entries in auth_user which are not in userdetails table. If found update userdetails table.
I hope i solved it and it's seems fine now:
Here is views.py code
def index(request):
update_user_details()
return render_to_response("larb/index.html",
RequestContext(request))
def update_user_details():
id_past_entries = UserDetails.objects.all().values_list('user_id', flat = True)
new_entries = User.objects.exclude(id__in=id_past_entries)
if new_entries:
for new_id in new_entries:
new = User.objects.get(id=new_id)
UserDetails.objects.create(user=new)
UserDetails.save()

Zendframework 2 postgresql update with "not"

Is is possible to pass to database the following sql query using tableGateway, if so, how would such a command look like ?
UPDATE table_data SET active = not active where table_data.id = 12;
You need to use a Zend\Db\Sql\Expression, this class tells Zend\Db that you know what you're doing and that the content of the string passed to this class shouldn't be transformed, but rather used as is.
// build the table gateway object
$adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$tableIdentifier = new TableIdentifier('table_data', 'public');
$tableGateway = new TableGateway($tableIdentifier, $adapter);
// create the filter
$where = new \Zend\Db\Sql\Where();
$where->equalTo('id', '12');
// update table
$tableGateway->update(
['active' => new \Zend\Db\Sql\Expression('not active')],
$where
);

many to many relation gorm table

I have a little problem filtering data...I have a relation many to many.
Sponsor and Old
I have one intermediary table with both ids...
When I log in, my session save a Sponsor id...but when I go to see Old view, appears every Olds... How to access the intermediary table from the OldController or the SponsorController?
In my Oldcontroller I have:
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
def sponsor = Sponsor.findById(session.getAttribute("id"))
def myOld = Old.findAllBySponsor(sponsor, params)
def allMyOld = Old.findAllBySponsor(sponsor)
respond myOld, model:[oldInstanceCount: allMyOld.size()]
//respond Old.list(params), model:[oldInstanceCount: Old.count()]
}
But returns unexpected NullpointerException when processing request: [GET] /oldCare/old/index
No value specified for parameter 2.. Stacktrace follows:
Message: No value specified for parameter 2.
How I access the intermediary table for filtering the olds and appears just the Old associated a one Sponsor?
Assuming you have the following :
class Old {
String title
static hasMany = [sponsours: Sponsour]
}
class Sponsour {
String name
static hasMany = [olds:Old]
}
To find :
def sponsor = Sponsor.load(session.getAttribute("id"))
def allMyOlds = Old.findBySponsour(sponsor,params)

How can I insert and get PK Id using Entity Framework?

currently I'm Inserting like:
MyNamedEntities db = new MyNamedEntities();
MyTableEntity field = new MyTableEntity();
field.Name = "me";
db.MyTableEntity.AddObject(field);
db.SaveChanges()
But now I want to insert child elements and I need that field.Id part
MyOtherTableEntity field = new MyOtherTableEntity();
field.TableId = new MyTableEntity.First(x => x.Id.Equals( ... ));
How can I get the field.Id ?
If your table has defined the Id as an INT IDENTITY column, then you don't really have to do anything at all! :-)
In that case, just insert your entity and after the call to .SaveChanges(), your object should contain the new Id value:
MyTableEntity field = new MyTableEntity();
field.Name = "me";
db.MyTableEntity.AddObject(field);
db.SaveChanges();
int newID = field.Id;
You can also just add them to the parent by the association before or after the save changes
Something like this.
address a = new address();
a.city = "Detroit";
field.address.add(a);
db.SaveChanges();