I'm creating table that show objects of a model and I have a SerializerMethodField that shows a value from a different table with same transaction ID.
The problem is I'm using the serializers for the filtering table and chargeback is not working in there. How Can I make it filterable?
Simplifying the code, a have this model:
class PSerializer(serializers.ModelSerializer):
...
chargeback = serializers.SerializerMethodField()
def get_value(self, obj):
ctransaction = CTransaction.objects.raw('SELECT * '
'FROM ctransaction '
'WHERE TRIM(mid)=TRIM(%s) '
'AND TRIM(unique_id)=TRIM(%s) '
'AND TRIM(num)=TRIM(%s) '
'AND rc_code IN (%s, %s, %s)',
[obj.mid, obj.unique_id, obj.num, '1', '1', '1'])
if len(cs_transaction) > 0:
return 'Yes'
return 'No'
If I understand your question correctly, your problem is the method name (get_value). you should change it to get_chargeback
class PSerializer(serializers.ModelSerializer):
...
chargeback = serializers.SerializerMethodField()
def get_chargeback(self, obj):
ctransaction = CTransaction.objects.raw('SELECT * '
'FROM ctransaction '
'WHERE TRIM(mid)=TRIM(%s) '
'AND TRIM(unique_id)=TRIM(%s) '
'AND TRIM(num)=TRIM(%s) '
'AND rc_code IN (%s, %s, %s)',
[obj.mid, obj.unique_id, obj.num, '1', '1', '1'])
if len(cs_transaction) > 0:
return 'Yes'
return 'No'
Related
HI I have a customer field and the default search is by name, and I want to add a search by barcode as well to the customer field
I have tried adding a barcode(partner_id.barcode) on the domain as below, but it still doesn't work (model = sale.order)
#api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
if self._context.get('sale_show_partner_name'):
if operator == 'ilike' and not (name or '').strip():
domain = []
elif operator in ('ilike', 'like', '=', '=like', '=ilike'):
domain = expression.AND([
args or [],
['|', '|', ('name', operator, name), ('partner_id.name', operator, name), ('partner_id.barcode', operator, name)]
])
return self._search(domain, limit=limit, access_rights_uid=name_get_uid)
return super(SaleOrder, self)._name_search(name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid)
I have also tried in the (res.partner) model as below. it can search customer by barcode, but cannot search customer by name :
#api.model
def name_search(self, name, args=None, operator='ilike', limit=100):
if not self.env.context.get('display_barcode', True):
return super(ResPartnerInherit, self).name_search(name, args, operator, limit)
else:
args = args or []
recs = self.browse()
if not recs:
recs = self.search([('barcode', operator, name)] + args, limit=limit)
return recs.name_get()
What should I do if I want to find a customer by name and barcode?
If anyone knows, please let me know
Best Regards
The barcode field in res.partner is a property field and stored in ir.property model which name is Company Propeties in Odoo and you can access it with developer mode from Settings -> Technical -> Company Propeties.
The _name_search method for res.partner enable you to search in any Many2one partner relation field in any model by one of these fields display_name, email, reference and vat and you can override it to add barcode as below:
from odoo import api, models
from odoo.osv.expression import get_unaccent_wrapper
import re
class ResPartner(models.Model):
_inherit = 'res.partner'
#api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
self = self.with_user(name_get_uid) if name_get_uid else self
# as the implementation is in SQL, we force the recompute of fields if necessary
self.recompute(['display_name'])
self.flush()
print(args)
if args is None:
args = []
order_by_rank = self.env.context.get('res_partner_search_mode')
if (name or order_by_rank) and operator in ('=', 'ilike', '=ilike', 'like', '=like'):
self.check_access_rights('read')
where_query = self._where_calc(args)
self._apply_ir_rules(where_query, 'read')
from_clause, where_clause, where_clause_params = where_query.get_sql()
from_str = from_clause if from_clause else 'res_partner'
where_str = where_clause and (" WHERE %s AND " % where_clause) or ' WHERE '
print(where_clause_params)
# search on the name of the contacts and of its company
search_name = name
if operator in ('ilike', 'like'):
search_name = '%%%s%%' % name
if operator in ('=ilike', '=like'):
operator = operator[1:]
unaccent = get_unaccent_wrapper(self.env.cr)
fields = self._get_name_search_order_by_fields()
query = """SELECT res_partner.id
FROM {from_str}
LEFT JOIN ir_property trust_property ON (
trust_property.res_id = 'res.partner,'|| {from_str}."id"
AND trust_property.name = 'barcode')
{where} ({email} {operator} {percent}
OR {display_name} {operator} {percent}
OR {reference} {operator} {percent}
OR {barcode} {operator} {percent}
OR {vat} {operator} {percent})
-- don't panic, trust postgres bitmap
ORDER BY {fields} {display_name} {operator} {percent} desc,
{display_name}
""".format(from_str=from_str,
fields=fields,
where=where_str,
operator=operator,
email=unaccent('res_partner.email'),
display_name=unaccent('res_partner.display_name'),
reference=unaccent('res_partner.ref'),
barcode=unaccent('trust_property.value_text'),
percent=unaccent('%s'),
vat=unaccent('res_partner.vat'), )
where_clause_params += [search_name] * 4 # for email / display_name, reference
where_clause_params += [re.sub('[^a-zA-Z0-9\-\.]+', '', search_name) or None] # for vat
where_clause_params += [search_name] # for order by
if limit:
query += ' limit %s'
where_clause_params.append(limit)
print(query)
print(where_clause_params)
self.env.cr.execute(query, where_clause_params)
return [row[0] for row in self.env.cr.fetchall()]
return super(ResPartner, self)._name_search(name, args, operator=operator, limit=limit, name_get_uid=name_get_uid)
Edit
I think its something related to django-fsm, have a look at this code I wrote for States
class STATE:
SUBMITTED = 'Submitted'
VERIFIED_BY_DA = 'Verified by DA'
APPROVED_BY_MS = 'Verified by MS'
APPROVED_BY_DR = 'Approved by DR'
APPROVED_BY_SrAO = 'Approved by SAO.'
APPROVED_BY_R = 'Approved by R'
AMOUNT_TRANSFERRED = 'Accepted'
REJECT = 'Rejected'
def __init__(self):
pass
STATE_CHOICES = (
(STATE.SUBMITTED, 'Submitted', 'Medical'),
(STATE.VERIFIED_BY_DA, 'Verified by DA', 'Medical'),
(STATE.APPROVED_BY_MS, 'Approved by MD', 'Medical'),
(STATE.APPROVED_BY_DR, 'Approved by DR', 'Medical'),
(STATE.APPROVED_BY_SrAO, 'Approved by SAO', 'Medical'),
(STATE.APPROVED_BY_R, 'Approved by R', 'Medical'),
(STATE.AMOUNT_TRANSFERRED, 'Amount transferred by AD', 'Medical'),
(STATE.REJECT, 'Reject', 'Medical'),
)
So I have these two models defined in separate file under models folder in django
First I defined only Medical model and everything was working fine
from django_fsm import FSMField
from state import STATE
from state import STATE_CHOICES
class Medical(BaseModel):
general_detail = models.ForeignKey(
GeneralDetail,
help_text='General Detail'
)
state = FSMField(
blank=True,
protected=not settings.DEBUG,
default=STATE.SUBMITTED,
state_choices=STATE_CHOICES,
)
def __str__(self):
return str(self.general_detail.employee.user.first_name) + ' ' \
+ str(self.general_detail.employee.user.last_name)
def __unicode__(self):
return str(self.general_detail.employee.user.first_name) + ' ' \
+ str(self.general_detail.employee.user.last_name)
But just after adding this below model it gives error in django-admin when saving a field in transition history using django-admin.
class TransitionHistory(BaseModel):
state_from = FSMField(
blank=True,
protected=not settings.DEBUG,
default=STATE.SUBMITTED,
state_choices=STATE_CHOICES,
)
state_to = FSMField(
blank=True,
protected=not settings.DEBUG,
default=STATE.SUBMITTED,
state_choices=STATE_CHOICES,
)
def __str__(self):
return str(self.state_from) + str(self.state_to)
def __unicode__(self):
return str(self.state_from) + str(self.state_to)
Error
Exception Type: DoesNotExist
Exception Value: Medical matching query does not exist
Line 379
C:\Python27\lib\site-packages\django\db\models\query.py in get
self.model._meta.object_name
Just check if you have made migrations, if yes then there is a possibility that you might have forgotten registering your model in the admin.py
I want to add a new field when somebody checks an option in my web page ("Add column 'external id' ")
table = IssueTable(issue_list)
show_ext = request.GET.get('show_ext', 0)
if show_ext:
table._meta.fields = table._meta.fields + ('external_id',)
I thought doing that it was the solution but I didn't succeed. The external_id is part of the model. table._meta.fields doesnt get updated and of course I cannot see the column in the table when this one is rendered.
class IssueTable(tables.Table):
def render_id(self, value, record):
if record.status.upper() in ['RESOLVED', 'INVALID']:
return mark_safe('<s>#%s</s>' % (reverse('issues.views.view', args=(record.pk,)), record.pk))
else:
return mark_safe('#%s' % (reverse('issues.views.view', args=(record.pk,)), record.pk))
def render_title(self, value, record):
return mark_safe('%s' % (reverse('issues.views.view', args=(record.id,)), value))
class Meta(object):
model = Issue
fields = ('id', 'title', 'product', 'type', 'priority', 'status', 'created')
attrs = {'class': 'table table-bordered'}
empty_text = _('No records found')
Any ideas?
So, I think I'm having a hard time wrapping my head around python Dicts. I have a scraper , where I successfully managed to make a dictionary parsing through webpages; now its time to insert into items I have defined as scrapy Field
class ApplicationItem(Item):
Case_reference = Field()
Application_name = Field()
Contact_name = Field()
Contact_telephone = Field()
where I create a python Dictionary like this:
{u" Applicant's name: ": u' KIMARO COMPANY INC ',
u' Case reference: ': u' ARB/15/00696 ',
u' Contact name: ': u' ',
u' Contact telephone: ': u' 07957 140179 ' }
my question is how would I make sure that I am inserting the correct value from the dictionary to scrapy item.
I have this so far:
for res, rec in application.items():
item['Case_reference'] = application.get(result(res))
item['Application_name'] = application.get(result(res))
item['Contact_name'] = application.get(result(res))
item['Contact_telephone'] = application.get(result(res))
which I don not think would do what I expect! I am actually getting python typeError on this.
Any Idea?
item is an actual field that I am trying to insert. So it is an instance of ApplicationItem
item['Case_reference'] = application.get()
is the way I try to insert from a previously created dict into each field.
Since item is not a dictionary, you cannot call item['key'] = value.
Instead, use:
setattr(obj, attribute, value)
Try this code:
class ApplicationItem(Item):
ATTRIBUTE_MAPPINGS = {
" Applicant's name: " : "Application_name",
" Case refference " : "Case_reference",
" Contact name: " : "Contact_name",
"' Contact telephone: " : "Contact_telephone",
}
Case_reference = Field()
Application_name = Field()
Contact_name = Field()
Contact_telephone = Field()
And your loop would be:
for key, value in application.iteritems():
setattr(item, ApplicationItem.ATTRIBUTE_MAPPINGS[key], application.get(result(key)))
In Django, if you want to create a model you can do it as follows:
class SomeModel(models.Model):
a = models.CharField(max_length=10)
b = models.CharField(max_length=20)
c = models.CharField(max_length=30)
d = models.CharField(max_length=40)
e = models.CharField(max_length=50)
f = models.CharField(max_length=60)
Now if you want to create an instance in the shell, you have to do:
> abcdef = SomeModel(a="stuff", b="stuff", c="stuff", d="stuff", e="stuff", f="stuff")
This gets really annoying if you have to keep creating model instances with long property names. Is there a way to simply send the arguments like you would with a normal Python object (as in without having to name the variables and just send the variables in order) ?
Like this:
> abcdef = SomeModel("stuff", "stuff", "stuff", "stuff", "stuff", "stuff")
As you would with a standard Python class in the init function.
Thanks :)
Here is my actual Python model:
class School(models.Model):
urn = models.CharField(max_length=6)
name = models.CharField(max_length=100)
house = models.CharField(max_length=50)
street = models.CharField(max_length=50)
county = models.CharField(max_length=50)
postcode = models.CharField(max_length=8)
def __unicode__(self):
return str(
'URN: ' + self.urn + ', ' +
'Name: ' + self.name + ', ' +
'House: ' + self.house + ', ' +
'Street: ' + self.street + ', ' +
'County: ' + self.county + ', ' +
'Postcode: ' + self.postcode + ', '
)
Have you tried the following code:
obj = SomeModel(None, "a_stuff", "b_stuff", "c_stuff", "d_stuff", "e_stuff", "f_stuff")
obj.save()
Hope these helps.
you can create instance by doing
abcdef = SomeModel()
Since instantiating doesnot touch the database, you can assign values later and then do .save().