How can override default_get in odoo9? - python-2.7

I want to override default_get in odoo9 and My code
class account_payment(models.Model):
_inherit = "account.payment"
#api.model
def default_get(self, fields):
#print 'PRINT1',MAP_INVOICE_TYPE_PARTNER_TYPE
rec = super(account_payment, self).default_get(fields)
invoice_defaults = self.resolve_2many_commands('invoice_ids', rec.get('invoice_ids'))
if invoice_defaults and len(invoice_defaults) == 1:
invoice = invoice_defaults[0]
rec['communication'] = invoice['reference'] or invoice['name'] or invoice['number']
rec['currency_id'] = invoice['currency_id'][0]
rec['payment_type'] = invoice['type'] in ('out_invoice', 'in_refund', 'sponsor_invoice',) and 'inbound' or 'outbound' # modified for charity
rec['partner_type'] = MAP_INVOICE_TYPE_PARTNER_TYPE[invoice['type']]
rec['partner_id'] = invoice['partner_id'][0]
rec['amount'] = invoice['residual']
return rec
but when I click create it shows an error message, that point the inherited class first then calling base class, how is that possible? Please help.
Error message:
File "/opt/odoo_v9_charity/server/addons/web_charity/models/account_payment.py", line 87, in default_get
rec = super(account_payment_charity, self).default_get(fields)
File "/opt/odoo_v9_charity/server/openerp/api.py", line 248, in wrapper
return new_api(self, *args, **kwargs)
File "/opt/odoo_v9_charity/server/openerp/addons/account/models/account_payment.py", line 257, in default_get
rec['partner_type'] = MAP_INVOICE_TYPE_PARTNER_TYPE[invoice['type']]
KeyError: u'sponsor_out_invoice'

The dict/map MAP_INVOICE_TYPE_PARTNER_TYPE simply does not have the key 'sponsor_out_invoice'. Maybe you should add it.

Related

getting 'name' is an invalid keyword argument (using graphene-django)

i am using graphene and getting 'name' is an invalid keyword argument for GuestMutation error what is it related to?
//models.py
class Guest(models.Model):
name = models.CharField(max_length=100)
phone = models.IntegerField()
def __str__(self):
return self.name
//schema.py
class GuestType(DjangoObjectType):
class Meta:
model = Guest
fields = ('id','name','phone')
class GuestMutation (graphene.Mutation):
class Arguments:
name = graphene.String(required=True)
phone = graphene.Int(required=True)
guest = graphene.Field(GuestType)
#classmethod
def mutate(cls, root,info,name,phone):
guest = Guest(name=name, phone=phone)
guest.save()
return GuestMutation(name=name, phone=phone)
class Mutation(graphene.ObjectType):
add_guest = GuestMutation.Field()
error message
Traceback (most recent call last):
File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/promise/promise.py", line 489, in _resolve_from_executor
executor(resolve, reject)
File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/promise/promise.py", line 756, in executor
return resolve(f(*args, **kwargs))
File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise
return next(*args, **kwargs)
File "/home/ahmed/Documents/Django/Shalleh/booking/schema.py", line 66, in mutate
return GuestMutation(name=name, phone=phone)
File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/graphene/types/objecttype.py", line 169, in init
raise TypeError(
graphql.error.located_error.GraphQLLocatedError: 'name' is an invalid keyword argument for GuestMutation
You're returning the wrong information:
class GuestMutation (graphene.Mutation):
# What you accept as input
class Arguments:
name = graphene.String(required=True)
phone = graphene.Int(required=True)
# What you return as output
guest = graphene.Field(GuestType)
So as mentioned, you need to return the guest you created.

Nested Field Gives TypeError upon indexing in elasticsearch-dsl-py

Whenever i try to save an object that has a nested field i get a Type error.
TypeError: isinstance() arg 2 must be a type or tuple of types
I have following document classes:
class CreationIndex(InnerDoc):
created_by = Keyword()
created_date = Date()
class UpdationIndex(InnerDoc):
updated_by = Keyword()
updated_date = Date()
class IndustryIndex(DocType):
name = Text(analyzer= 'english')
creation = CreationIndex()
updation = Nested(UpdationIndex())
class Meta:
index = 'industry'
def bulk_indexing():
elastic_connection = Elasticsearch(hosts=['localhost'], timeout=20)
if elastic_connection.indices.exists('industry'):
elastic_connection.indices.delete('industry')
if elastic_connection.indices.exists('category'):
elastic_connection.indices.delete('category')
IndustryIndex.init()
print('HI')
bulk(client=elastic_connection, actions=(b.indexing() for b in models.Industry.objects.all()))
My Industry Model is a django model (where i have used mongoDB so itself is a dynamic document) which is defined as
class Industry(DynamicDocument,BaseCreationUpdation):
name=StringField(required=True,unique=True)
def save(self,*args,**kwargs):
'''
'''
self=save_created_updated_info(self)
super(Industry,self).save(args,kwargs)
def indexing(self):
objCreation = CreationIndex(
created_by = self.creation.created_by,
created_date = self.creation.created_date.date().isoformat()
)
print(objCreation.to_dict())
obj = IndustryIndex(
meta = {'id': str(self.id)},
name = self.name,
creation = objCreation.to_dict(),
updation = [],
)
for objUp in self.updation:
objUpdation = UpdationIndex(
updated_by = objUp.updated_by,
updated_date = objUp.updated_date.date().isoformat()
)
print(objUpdation)
obj.updation.append(objUpdation)
print()
print(obj.to_dict())
print()
obj.save()
return obj.to_dict(include_meta=True)
#classmethod
def index_document(cls,sender, document, **kwargs):
document.indexing()
Now whenever i run the bulk_indexing module it comes up with a problem :
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\projects\django\bhetincha\category\search.py", line 57, in bulk_indexing
bulk(client=elastic_connection, actions=(b.indexing() for b in models.Industry.objects.all()))
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch\helpers\__init__.py", line 257, in bulk
for ok, item in streaming_bulk(client, actions, **kwargs):
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch\helpers\__init__.py", line 180, in streaming_bulk
client.transport.serializer):
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch\helpers\__init__.py", line 58, in _chunk_actions
for action, data in actions:
File "D:\projects\django\bhetincha\category\search.py", line 57, in <genexpr>
bulk(client=elastic_connection, actions=(b.indexing() for b in models.Industry.objects.all()))
File "D:\projects\django\bhetincha\category\models.py", line 80, in indexing
obj.save()
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\document.py", line 405, in save
self.full_clean()
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\utils.py", line 417, in full_clean
self.clean_fields()
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\utils.py", line 403, in clean_fields
data = field.clean(data)
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\field.py", line 179, in clean
data = super(Object, self).clean(data)
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\field.py", line 90, in clean
data = self.deserialize(data)
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\field.py", line 81, in deserialize
for d in data
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\field.py", line 81, in <listcomp>
for d in data
File "C:\Users\prabi\Envs\bhetincha\lib\site-packages\elasticsearch_dsl\field.py", line 160, in _deserialize
if isinstance(data, self._doc_class):
TypeError: isinstance() arg 2 must be a type or tuple of types
Why is there this error? When i removed the updation filed which is nested it all works, though the creation field is the same. Whats the problem here?
The way you are initialising the nested field is wrong - you need to pass a class rather than an instance of the class as the argument to the constructor (i.e., drop the brackets):
updation = Nested(UpdationIndex) # Instead of Nested(UpdationIndex())

ManyToMany relation with a through model using factory_boy?

I'm facing the problem when creating the many to many relation with through model using factory. I followed this link factory recipies.
I'm getting the TypeError: 'datetime.date' object is not callable this error. Help me to find the solution.
I got an another error:
File "/local/lib/python2.7/site-packages/factory/base.py", line 492, in _generate
obj = cls._prepare(create, **attrs)
File "/local/lib/python2.7/site-packages/factory/base.py", line 467, in _prepare
return cls._create(model_class, *args, **kwargs)
File "/local/lib/python2.7/site-packages/factory/django.py", line 174, in _create
return manager.create(*args, **kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/query.py", line 346, in create
obj = self.model(**kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/base.py", line 480, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'a1' is an invalid keyword argument for this function
models.py
class TimeStampModel(models.Model):
start_date = models.DateField(_('Start Date'))
end_date = models.DateField(_('End Date'))
class Meta:
abstract = True
class User(models.Model):
name = models.CharField()
class Aclass(models.Model):
name = models.CharField()
user = models.ForeignKey(User)
report = models.ManyToManyField('self', through='Bcalss')
class Bcalss(TimeStampModel):
a1 = models.ForeignKey(Aclass)
b1 = models.ForeignKey(Aclass)
factories.py
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.User
name = "John Doe"
class AclassFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Aclass
user = factory.SubFactory(UserFactory)
name = "Admins"
class BclassFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Bclass
a1 = factory.SubFactory(AclassFactory)
b1 = factory.SubFactory(AclassFactory)
start_date = fuzzy.FuzzyDate(timezone.localtime(timezone.now())).date(), timezone.localtime(timezone.now())).date() + timedelta(days=2))
end_date = fuzzy.FuzzyDate(timezone.localtime(timezone.now())).date(), timezone.localtime(timezone.now())).date() + timedelta(days=6))
class AclassWithBclassFactory(AclassFactory):
reports = factory.RelatedFactory(BclassFactory, 'a1')
tests.py
class A1classModelTestCase(TestCase):
def test_a1class_create(self):
a1 = factories.AclassWithBclassFactory.create()
In this line:
start_date = factory.LazyAttribute(datetime.today)
You need to actually call the function with ():
start_date = factory.LazyAttribute(datetime.today())

Difficulty serializing Geography column type using sqlalchemy marshmallow

I an trying to use Marshmallow to do do deserialize and serialise SQLAlchemy objects but run into a problem when dealing with Geography fields in the ORM.
Firstly the model:
class Address(db.Model, TableColumnsBase):
__tablename__ = 'address'
addressLine1 = db.Column(String(255), nullable=True, info="Street address, company name, c/o")
addressLine2 = db.Column(String(255), nullable=True, info="Apartment, suite, unit, building floor, etc")
countryCode = db.Column(String(255), nullable=True, info="Country code such as AU, US etc")
suburb = db.Column(String(255), nullable=True, info="Users suburb such as Elizabeth Bay")
postcode = db.Column(String(32), nullable=True, info="Users postcode such as 2011 for Elizabeth Bay")
state = db.Column(String(64), info="State for user such as NSW")
user_presence = one_to_many('UserPresence', backref = 'user', lazy='select', cascade='all, delete-orphan')
location = Column(Geography(geometry_type='POINT', srid=4326))
discriminator = Column('type', String(50))
__mapper_args__ = {'polymorphic_on': discriminator}
def as_physical(self):
pa = { # TODO - stub, make it proper
"latitude": 2.1,
"longitude": 1.1,
"unitNumber": '1',
"streetNumber": self.addressLine1,
"streetName": self.addressLine2,
"streetType": 'street',
"suburb": self.suburb,
"postcode": self.postcode
}
return pa
Secondly the marshmallow schema:
class AddressSchema(ModelSchema):
class Meta:
model = Address
sqla_session
Then the error when trying to run:
/Users/james/.virtualenvs/trustmile-api-p2710/bin/python /Users/james/Documents/workspace/trustmile-backend/trustmile/tests/postgis_scratch.py
Traceback (most recent call last):
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/tests/postgis_scratch.py", line 1, in <module>
from app import db
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/app/__init__.py", line 54, in <module>
from app.api.consumer_v1 import bp as blueprint
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/app/api/__init__.py", line 4, in <module>
import courier_v1
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/app/api/courier_v1/__init__.py", line 5, in <module>
from .routes import routes
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/app/api/courier_v1/routes.py", line 10, in <module>
from .api.nearestNeighbours_latitude_longitude import NearestneighboursLatitudeLongitude
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/app/api/courier_v1/api/__init__.py", line 5, in <module>
from app.ops import requesthandler
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/app/ops/requesthandler.py", line 1, in <module>
from app.ops.consumer_operations import cons_ops, ConsumerOperationsFactory
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/app/ops/consumer_operations.py", line 19, in <module>
from app.users.serialize import ApplicationInstallationSchema, UserAddressSchema, ConsumerUserSchema, CourierUserSchema
File "/Users/james/Documents/workspace/trustmile-backend/trustmile/app/users/serialize.py", line 40, in <module>
class AddressSchema(ModelSchema):
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/marshmallow/schema.py", line 116, in __new__
dict_cls=dict_cls
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/marshmallow_sqlalchemy/schema.py", line 57, in get_declared_fields
declared_fields = mcs.get_fields(converter, opts)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/marshmallow_sqlalchemy/schema.py", line 90, in get_fields
include_fk=opts.include_fk,
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/marshmallow_sqlalchemy/convert.py", line 77, in fields_for_model
field = self.property2field(prop)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/marshmallow_sqlalchemy/convert.py", line 95, in property2field
field_class = self._get_field_class_for_property(prop)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/marshmallow_sqlalchemy/convert.py", line 153, in _get_field_class_for_property
field_cls = self._get_field_class_for_column(column)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/marshmallow_sqlalchemy/convert.py", line 123, in _get_field_class_for_column
return self._get_field_class_for_data_type(column.type)
File "/Users/james/.virtualenvs/trustmile-api-p2710/lib/python2.7/site-packages/marshmallow_sqlalchemy/convert.py", line 145, in _get_field_class_for_data_type
'Could not find field column of type {0}.'.format(types[0]))
marshmallow_sqlalchemy.exceptions.ModelConversionError: Could not find field column of type <class 'geoalchemy2.types.Geography'>.
I've tried a few overrides on the location field however to no avail. Any help much appreciated.
Updated Jan 24 2016
This is my code as it stands as the moment with a simpler model:
The SQLAlchemyModel:
class Location(db.Model, TableColumnsBase):
__tablename__ = "location"
loc = db.Column(Geography(geometry_type='POINT', srid=4326))
The marshmallow_sqlalchemy schema object
class LocationSchema(ModelSchema):
loc = GeographySerializationField(attribute='loc')
class Meta:
model = Location
sqla_session = db.session
model_converter = GeoConverter
Other plumbing as per suggestions:
class GeoConverter(ModelConverter):
SQLA_TYPE_MAPPING = ModelConverter.SQLA_TYPE_MAPPING.copy()
SQLA_TYPE_MAPPING.update({
Geography: fields.Str
})
class GeographySerializationField(fields.Field):
def _serialize(self, value, attr, obj):
if value is None:
return value
else:
if isinstance(value, Geography):
return json.dumps({'latitude': db.session.scalar(geo_funcs.ST_X(value)), 'longitude': db.session.scalar(geo_funcs.ST_Y(value))})
else:
return None
def _deserialize(self, value, attr, data):
"""Deserialize value. Concrete :class:`Field` classes should implement this method.
:param value: The value to be deserialized.
:param str attr: The attribute/key in `data` to be deserialized.
:param dict data: The raw input data passed to the `Schema.load`.
:raise ValidationError: In case of formatting or validation failure.
:return: The deserialized value.
.. versionchanged:: 2.0.0
Added ``attr`` and ``data`` parameters.
"""
if value is None:
return value
else:
if isinstance(value, Geography):
return {'latitude': db.session.scalar(geo_funcs.ST_X(value)), 'longitude': db.session.scalar(geo_funcs.ST_Y(value))}
else:
return None
In running the code:
from app.users.serialize import *
from app.model.meta.schema import Location
l = LocationSchema()
loc = Location(27.685994, 85.317815)
r = l.load(loc)
print r
The result I get is:
UnmarshalResult(data={}, errors={u'_schema': [u'Invalid input type.']})
You can override ModelConverter class and specify custom mapping for your geography field. See Jair Perrut's answer here How to use marshmallow to serialize a custom sqlalchemy field?
from marshmallow_sqlalchemy import ModelConverter
from marshmallow import fields
class GeoConverter(ModelConverter):
SQLA_TYPE_MAPPING = ModelConverter.SQLA_TYPE_MAPPING.copy()
SQLA_TYPE_MAPPING.update({
Geography: fields.Str
})
class Meta:
model = Address
sqla_session = session
model_converter = GeoConverter
Solved it, firstly was misusing the methods but here is the answer:
For serialisation:
class GeoConverter(ModelConverter):
SQLA_TYPE_MAPPING = ModelConverter.SQLA_TYPE_MAPPING.copy()
SQLA_TYPE_MAPPING.update({
Geography: fields.Str
})
class GeographySerializationField(fields.String):
def _serialize(self, value, attr, obj):
if value is None:
return value
else:
if attr == 'loc':
return {'latitude': db.session.scalar(geo_funcs.ST_X(value)), 'longitude': db.session.scalar(geo_funcs.ST_Y(value))}
else:
return None
def _deserialize(self, value, attr, data):
"""Deserialize value. Concrete :class:`Field` classes should implement this method.
:param value: The value to be deserialized.
:param str attr: The attribute/key in `data` to be deserialized.
:param dict data: The raw input data passed to the `Schema.load`.
:raise ValidationError: In case of formatting or validation failure.
:return: The deserialized value.
.. versionchanged:: 2.0.0
Added ``attr`` and ``data`` parameters.
"""
if value is None:
return value
else:
if attr == 'loc':
return WKTGeographyElement('POINT({0} {1})'.format(str(value.get('longitude')), str(value.get('latitude'))))
else:
return None
The schema definition:
class LocationSchema(ModelSchema):
loc = GeographySerializationField(attribute='loc')
id = fields.UUID(Location, attribute='id')
class Meta:
model = Location
sqla_session = db.session
model_converter = GeoConverter
And the test:
from app.users.serialize import *
from app.model.meta.schema import Location
from app import db
l = LocationSchema()
loc = Location(27.685994, 85.317815)
db.session.add(loc)
db.session.commit()
r = l.dump(loc).data
print r
loc_obj = l.load(r)
print loc_obj.data

Filter Models based on content type django 1.7

My models.py looks like
class OneTimeEvent(models.Model):
title = models.CharField(max_length = 160)
location = models.CharField(max_length = 200, blank = True)
event_date = models.DateTimeField('event date',blank = True, null = True)
price = models.IntegerField(max_length = 20, blank = True, null = True)
seats = models.IntegerField(max_length = 20, blank = True, null = True)
abstract = models.TextField()
event_plan = models.TextField()
available_seats = models.IntegerField(max_length = 20, blank = True, null = True)
booked_seats = models.IntegerField(max_length = 20, blank = True, null = True)
byt_url = models.CharField(max_length = 160, blank = True)
tags = models.TextField()
class RecurringEvent(models.Model):
title = models.CharField(max_length = 160)
location = models.CharField(max_length = 200, blank = True)
price = models.IntegerField(max_length = 10)
class Event(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
event_type = generic.GenericForeignKey('content_type', 'object_id')
I want to get the list of IDs of "OneTimeEvent" from "Event" model.
In python shell when I'm doing something like
>>> event = Event.objects.get(pk = 1)
>>> event.content_type
<ContentType: one time event>
From above code I can know that "content type of the event whose primary key is one time event" but when I do
>>> Event.objects.filter(content_type = "one time event")
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 691, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 709, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1287, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1314, in _add_q
current_negated=current_negated, connector=connector)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1181, in build_filter
lookups, value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 1545, in get_lookup_constraint
lookup_class(Col(alias, target, source), val), AND)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/lookups.py", line 82, in __init__
self.rhs = self.get_prep_lookup()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/lookups.py", line 85, in get_prep_lookup
return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 646, in get_prep_lookup
return self.get_prep_value(value)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 915, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'one time event'
>>>
I get this error.
One similar question is asked earlier Filter 2 models with ContentType in Django, I tried same but with this solution I get the empty list
>>> Event.objects.filter(content_type__model = 'OneTimeEvent')
[]
What should I do.
Thanks in advance
content_type is a foreign key to the ContentType model. That model has various manager methods, among them get_for_model, which takes a model class (note, not a string) and returns the relevant ContentType object. So:
ct = ContentType.objects.get_for_model(OneTimeEvent)
Event.objects.filter(content_type=ct)