Flask appbuilder how to use existing model to create a new model and save into DB - flask-sqlalchemy

Basically I have model A and B .
class A(ModelView):
datamodel = SQLAInterface(Tabel_A)
and
class B(ModelView):
datamodel = SQLAInterface(Table_B)
A has a action like :
#action("mularchive", "Archieve", "Archieve all Really?", "fa-rocket", single=False)
def mularchive(self, items):
self.update_redirect()
for item in items:
new_item = item.__class__()
new_item.name = item.name
B.add(new_item)
return redirect(self.get_redirect())
So I'm expect object b will save into table B.
But this is not working and it complain about
AttributeError: 'Table A' object has no attribute 'method_permission_name'
please help, I'm new to flask appbuilder and python... not sure where I made mistake .

for item in items
b = B(name = item.name)
db.session.add(b)
db.session.commit()
self.update_redirect()
return redirect(self.get_redirect())

Related

Django restframework SerializerMethodField background work

I am writing a project in Django with rest framework by using SerializerMethodField. This method makes queries for every row to get data, or View collects all queries and send it to DB? Django can make it as one joint query?
class SubjectSerializer(serializers.ModelSerializer):
edu_plan = serializers.SerializerMethodField(read_only=True)
academic_year_semestr = serializers.SerializerMethodField(read_only=True)
edu_form = serializers.SerializerMethodField(read_only=True)
def get_edu_plan(self, cse):
return cse.curriculum_subject.curriculum.edu_plan.name
def get_academic_year_semestr(self, cse):
semester = cse.curriculum_subject.curriculum.semester
return {'academic_year': semester.academic_year, 'semester': semester}
def get_edu_form(self, cse):
return cse.curriculum_subject.curriculum.edu_form.name
class Meta:
model = CurriculumSubjectEmployee
fields = [
'id',
'name',
'edu_plan',
'academic_year_semestr',
'edu_form'
]
class SubjectViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = SubjectSerializer
def get_queryset(self):
contract = self.request.user.employee.contract
if contract is None:
raise NotFound(detail="Contract not found", code=404)
department = contract.department
cses = CurriculumSubjectEmployee\
.objects\
.filter(curriculum_subject__department=department)
return cses

How to update a field in Model B using onchange in the field of model A ? Odoo 12

What i'm trying to achieve is ,When updating a field in model A ,i needs to update a field in model B using onchange method
_name = 'Model_A'
health_profile = fields.Many2one('health.profile', domain="[('partner_id', '=', partner_id)]", string="Health Profile")
#api.onchange('health_profile')
def get_health_profile_specialist(self):
ctx = self.health_profile.id
res = self.env['model_B'].browse(ctx)
return res.update({'specialist_name': self.specialist_name})
From what I understand there is no need to modify the field with an onchange. You can directly check the value in the model A field, you could directly use a related field
health_profile = fields.Many2one('health.profile', domain="[('partner_id', '=', partner_id)]", string="Health Profile")
specialist_id = fields.Many2one('<yourmodel>', related='health_profile.specialist_id')
Maybe you should explain yourself better.

Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "field-detail"

I know that this inconvenient is very presented, may be that I need learn more about of serializer relationships
I have the following model:
class Field(models.Model):
FIELD_TYPE_NATURE = 'Grama natural'
FIELD_TYPE_ARTIFICIAL = 'Grama sintetica'
FIELD_TYPE_CHOICES = (
(FIELD_TYPE_NATURE, u'Grama natural'),
(FIELD_TYPE_ARTIFICIAL, u'Grama sintetica'),
)
MODALITY_11 = 'Fútbol 11'
MODALITY_8 = 'Fútbol 8'
MODALITY_CHOICES = (
(MODALITY_11, u'Fútbol 11'),
(MODALITY_8, u'Fútbol 8'),
)
name = models.CharField(
max_length=150,
unique=True,
db_index=True,
primary_key=True,
)
field_type = models.CharField(
choices=FIELD_TYPE_CHOICES,
default=False,
blank=False,
max_length=20,
verbose_name=('Tipo de material/grama de la cancha')
)
modality = models.CharField(
max_length=40,
blank=False,
verbose_name='Modalidad'
)
photo = models.ImageField(upload_to='fields', blank=True, null=True)
location = models.CharField(max_length=150, blank=False)
def __str__(self):
return '%s %s %s' % (self.name, self.field_type, self.location)
My serializer is the following:
class FieldSerializer(serializers.HyperlinkedModelSerializer):
#url = serializers.HyperlinkedIdentityField(view_name='field-detail',)
class Meta:
model = Field
fields = ('url', 'name','field_type','modality','photo','location')
My viewset is:
class FieldViewSet(viewsets.ModelViewSet):
queryset = Field.objects.all()
serializer_class = FieldSerializer
This is my router:
router = routers.DefaultRouter()
router.register(r'fields', FieldViewSet)
And my url:
...
url(r'^api/', include(router.urls)),
...
When I go to the http://localhost:8000/api/fields/ url I get the following message:
File "/home/bgarcial/.virtualenvs/fuupbol2/lib/python3.5/site-packages/rest_framework/relations.py", line 386, in to_representation
raise ImproperlyConfigured(msg % self.view_name)
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for **hyperlinked relationship using view name "field-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.**
[11/Nov/2016 16:39:53] "GET /api/fields/ HTTP/1.1" 500 187477
When I use HyperlinkedIdentityField in my FieldSerializer class:
class FieldSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='field-detail',)
class Meta:
model = Field
fields = ('url', 'name','field_type','modality','photo','location')
I follow getting the same error.
Althought when I go to the url http://localhost:8000/api/fields/ I want get is a list of my objects, then is possible that I should put:
url = serializers.HyperlinkedIdentityField(view_name='field-list',)
?
I use HyperlinkedIdentityField according to:
This field can be applied as an identity relationship, such as the
'url' field on a HyperlinkedModelSerializer. It can also be used for
an attribute on the object.
I put the field-list in my view_name attribute and I get the error related
Could not resolve URL for hyperlinked relationship using view name "field-list". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
I don't understand the situations when I should use view_name attribute in relation to if I wnt get a list objects, a object detail and so ... although here explain something about it.
When I should use HyperlinkedModelSerializer and ModelSerializer

Custom field default value - populate with other entries from same field

I have created a custom module with extra fields on the product screen. I am trying to have the default value be a drop down with all of the entries already submitted to that field or the option to create a new entry (same as the default value when adding a product to a BOM).
class product_part_detail(osv.osv):
_inherit = 'product.template'
_columns = {
'x_mfrname1': fields.char('P/N'),
}
_defaults ={
'x_mfrname1': get_default_name,
}
def get_default_name(self):
return "test"
I tried creating a many2one field that refers to a field in a different table but I keep getting an error when trying to install the module. Below is the updated code that I am having issues with. Thanks in advance!
class product_part_detail(osv.osv):
_inherit = 'product.template'
_name = 'product.part.detail'
_columns = {
'x_mfrname1': fields.many2one('product.part.detail.fill', 'x_mfrname1id'),
'x_mfrname2': fields.many2one('product.part.detail.fill', 'x_mfrname1id'),
}
class product_part_detail_fill(osv.osv):
_name = 'product.part.detail.fill'
def _sel_func(self, cr, uid, context=None):
obj = self.pool.get('product.part.detail')
ids = obj.search(cr, uid, [])
res = obj.read(cr, uid, ids, ['x_mfrname1', 'x_mfrname2'], context)
res = [(r['x_mfrname1'], r['x_mfrname2']) for r in res]
return res
_columns = {
'x_mfrname1id': fields.one2many('product.part.detail', 'x_mfrname1', 'x_mfrname2', selection=_sel_func),
}
A couple of things. The idea of a drop down of the values they have previously entered requires a many2one field. You would create another model and then make x_mfrname1 a many2one to that table. As long as the user has create access on that table they will get a create option on the drop down to key new values.
One other item, as you are using the pre-8 API, the method signature of your default method should be:
def get_default_name(self, cr, uid, context=None):

How to create records before load the form view on new record in odoo?

I have the following models:
class Order(models.Model):
_name = 'discount_order.order'
partner_id = fields.Many2one('res.partner','Cliente',required=True)
order_lines_ids = fields.One2many('discount_order.order_line', 'order_id', string="Lineas")
obs = fields.Text('Comentarios y observaciones')
class Order_line(models.Model):
_name = 'discount_order.order_line'
order_id = fields.Many2one('discount_order.order', string="Order")
cat_id = fields.Many2one('product.category')
disc_ask = fields.Float('Descuento solicitado')
obs = fields.Char('Comentarios por linea')
I need to create 1 'order_line' for each 'product.category' record, when the user press the new button on the form view. So the new 'order object', already has assigned 'order_lines_ids'
You can set default value of order_lines_ids of discount_order.order model.
Default value you can set from py as well as from xml file.
So when you create new record of model discount_order.order then order_lines_ids automatically set default values.