Hi guys i was using Odoo 10, Is there a way to search partner using vat number instead of partner name when creating invoice?
Thanks in advance
Yes. There is a way to do that. You can try my solution
Add a context in the partner field to set, that you want to search by vat. Here you can use xpath.
context="{'search_by_vat': True}"
Overwrite the function name_search in res.partner:
class Partner(models.Model):
_inherit = 'res.partner'
#api.model
def name_search(self, name='', args=None, operator='ilike', limit=100):
if self._context.get('search_by_vat', False):
if name:
args = args If i Want to search in both name and vat what should i do?if args else []
args.append(['vat', 'ilike', name])
name = ''
return super(Partner, self).name_search(name=name, args=args, operator=operator, limit=limit)
If i Want to search in both name and vat what should i do?
You can use ['name', 'ilike', name] or ['vat', 'ilike', name]
class Partner(models.Model):
_inherit = 'res.partner'
#api.model
def name_search(self, name='', args=None, operator='ilike', limit=100):
if self._context.get('search_by_vat', False):
if name:
args = args if args else []
args.extend(['|', ['name', 'ilike', name], ['vat', 'ilike', name]])
name = ''
return super(Partner, self).name_search(name=name, args=args, operator=operator, limit=limit)
Related
Seems I need to apply a dot notation to CurrentUserDefault() object, tried .id but failed
class DotPrivateSerializer(serializers.ModelSerializer):
tag = serializers.SerializerMethodField()
def get_tag(self,obj):
queryset=TagPrivate.objects.filter(user=serializers.CurrentUserDefault) # <--TypeError
return TagPrivateSerializer(queryset).data
models.py
class DotPrivate(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
name = models.CharField(max_length=255)
description = models.TextField(max_length=350, blank=True)
lon = models.CharField(max_length=20)
lat = models.CharField(max_length=20)
rating = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(5.0)])
tag = models.ForeignKey('TagPrivate', on_delete=models.PROTECT)
in the following link in the first answer I found some solution but I do not completly understand it:
'CurrentUserDefault' object has no attribute 'user'
class TagPrivateSerializer(serializers.ModelSerializer):
class Meta:
model = TagPrivate
fields = ('id', 'name')
read_only_fields = ('id',)
You can not use CurrentUserDefault, this is just a value that the Django serializer will use for a default=… parameter, and then later swap for the request user.
You can fetch this from the request in the context, so:
class DotPrivateSerializer(serializers.ModelSerializer):
tag = serializers.SerializerMethodField()
def get_tag(self, obj):
queryset = TagPrivate.objects.filter(user=self.context['request'].user)
return TagPrivateSerializer(queryset).data
In the ModelViewSet, you will need to pass the user, so:
class DotPrivateViewSet(ModelViewSet):
queryset = # …
permission_classes = # …
serializer_class = DotPrivateSerializer
def get_serializer_context(self):
context = super().get_serializer_context()
context.update(request=self.request)
return context
I'm working with serializers as described by the link:Serializer relations (section PrimaryKeyRelatedField)
I have a slight different need, I'm sure it's really easy.
class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks')
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class SomeWidget(models.Model):
album = models.ForeignKey(Album)
track = models.ForeignKey(Track)
name = models.CharField(max_length=100)
description = models.CharField(max_length=100)
My need, I need to return the following:
{
'album_name': 'Things We Lost In The Fire',
'artist': 'Low',
'tracks': [
'1: Sunflower',
'2: Whitetail',
'3: Dinosaur Act',
...
],
'widget': [
{
'id': '1234',
'name': 'my widget',
'description': 'my description'
}
]
}
I am trying:
class WidgetField(serializers.RelatedField):
def to_representation(self, value):
return {
'id': '1234'
....
}
class TrackListingField(serializers.RelatedField):
def to_representation(self, value):
...
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackListingField(many=True)
widget = WidgetField()
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
I keep getting the error:
AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`.
Thanks
Ok, got it. It took a little bit of Googling / trial and error. Apparently you can override the function that returns data for the field.
For example:
class AlbumSerializer(serializers.ModelSerializer):
widget = serializers.SerializerMethodField()
def get_widget(self, data):
return {
'id': data.id
}
OR, you can do the following:
class WidgetSerializer(serializers.ModelSerializer):
class Meta:
model = Widget
fields = ('id', 'name', 'description',)
.... and in the AlbumSerializer.get_widget function:
def get_widget(self, data):
widget = Widget.objects.get(album=data.album, track=data.track)
return WidgetSerializer(widget, many=False, context=self.context).data
Finally, you don't have to use the function name "get_widget". You can name it whatever you want. Example:
class AlbumSerializer(serializers.ModelSerializer):
widget = serializers.SerializerMethodField("fn_override")
def fn_override(self, data):
....
You can follow the pattern in this SO question: Django REST Framework: adding additional field to ModelSerializer
I am adding a field to the user by using the recommend method here. #3 How can I update UserProfile assigned to User model?
When I attempt to save zip code on the /rest-auth/user/ url I get the exception "User has no userprofile."
model:
class UserProfile(models.Model):
user = models.OneToOneField(User)
# custom fields for user
zip_code = models.CharField(max_length=5)
serializer:
class UserSerializer(UserDetailsSerializer):
zip_code = serializers.CharField(source="userprofile.zip_code")
class Meta(UserDetailsSerializer.Meta):
fields = UserDetailsSerializer.Meta.fields + ('zip_code',)
def update(self, instance, validated_data):
profile_data = validated_data.pop('userprofile', {})
zip_code = profile_data.get('zip_code')
instance = super(UserSerializer, self).update(instance, validated_data)
# get and update user profile
profile = instance.userprofile
if profile_data and zip_code:
profile.zip_code = zip_code
profile.save()
return instance
Thank in advance!
I have the following serializer:
class WidgetSerializer(serializers.ModelSerializer):
owner = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model=Widget
fields = ('id', 'title', 'description', 'username', 'code', 'owner', 'list')
The problem is that the 'list' field, which is a drop down, gives all lists whereas I only want it to display lists that are owned by the user currently logged in.
Here's the respective models:
class WidgetList(MPTTModel):
name = models.CharField(max_length=100)
description = models.CharField(max_length=1024)
owner = models.ForeignKey('MyUser')
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
def __str__(self):
return self.name
class MPTTMEta:
order_insertion_by = ['name']
class Widget(models.Model):
title = models.CharField(max_length=100)
description = models.CharField(max_length=1024)
username = models.CharField(max_length=50)
code = models.CharField(max_length=1024)
owner = models.ForeignKey('MyUser', related_name='MyUser_owner')
list = models.ForeignKey('WidgetList')
I am a beginner in django. I hope that I could help.
Just try this
WidgetList.objects.filter(owner=request.user)
I have to limit it through a SlugRelatedField as per the documentation here -
http://www.django-rest-framework.org/api-guide/relations/#slugrelatedfield
I then used it like so -
list = serializers.SlugRelatedField(
queryset=WidgetList.objects.filter(owner=3),
many=True,
slug_field='name'
)
All I need to figure out now is to pass the serializers.CurrentUserDefault() in the filter for the queryset, or pass request.user.
Trying to add userprofile to user model
using: django rest framework. rest-auth module
But line profile = instance.userprofile giving error:*** django.db.models.fields.related.RelatedObjectDoesNotExist: User has no userprofile.
following instructions from here
Also, not sure on what is happening in super statement
Possible errors:
1.instance is not having userprofile after the super statement, hence profile = instance.userprofile statement giving error2.userprofile needs to be added to UserDetailsSerializer
UserDetailsSerializer
class UserDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('username', 'email', 'first_name', 'last_name')
read_only_fields = ('email', )
UserSerializer
class UserSerializer(UserDetailsSerializer):
company_name = serializers.CharField(source="userprofile.company_name")
class Meta(UserDetailsSerializer.Meta):
fields = UserDetailsSerializer.Meta.fields + ('company_name',)
def update(self, instance, validated_data):
profile_data = validated_data.pop('userprofile', {})
company_name = profile_data.get('company_name')
instance = super(UserSerializer, self).update(instance, validated_data)
# get and update user profile
profile = instance.userprofile
if profile_data and company_name:
profile.company_name = company_name
profile.save()
return instance
Do ask for more clarity if required.
Thanks in advance.
In the documentation it is assumed that userprofile was already created and now can be updated. You just need a check
# get and update user profile
try:
profile = instance.userprofile
except UserProfile.DoesNotExist:
profile = UserProfile()
if profile_data and company_name: