how can I get specific supplier for each product in sale order line in odoo? - odoo-10

I try to put the supplier in new field so when I select product in sale order line his supplier automatic appear in new field by this function : but did not work
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
_name = 'sale.order.line'
partner_name=fields.Char(compute='_count')
#api.depends()
def _count(self):
count = self.env['res.partner'].search([('name', '=', self.ids)])
self.partner_name = count

Related

Django Rest - get related data in M2M relation

I have 2 models:
class Artist(models.Model):
name = models.CharField(max_length=255)
music_type = models.CharField(max_length=50)
class Event(models.Model):
event_name = models.CharField(max_length=255)
description = models.TextField()
place = models.CharField(max_length=50)
longitude = models.DecimalField(max_digits=9, decimal_places=6)
latitude = models.DecimalField(max_digits=9, decimal_places=6)
date = models.DateField()
artists = models.ManyToManyField(Artist)
For every artist I would like to get list of other artists if they have ever been in any event together.
I was able to create close solution, but only for specific artist:
def get_related_artists(request):
artist_id = 2
related_events = Artist.objects.filter(id=artist_id).first().event_set.all()
related_artists_ids = []
for event in related_events:
related_artists_ids = related_artists_ids + list(event.artists
.all()
.values_list('id', flat=True)
.all())
related_artists = Artist.objects\
.filter(id__in=set(related_artists_ids))\
.exclude(id=artist_id)
serializer = ArtistRelatedSerializer(related_artists, many=True)
return JsonResponse(serializer.data, safe=False)
So firstly I get all event where specific artist took part. Later I iterate over this events and get other artist's ids. Another step is to remove duplicated ids and specific artist id. At the end I use serializer to return data.
Serializer looks like:
class ArtistRelatedSerializer(serializers.ModelSerializer):
class Meta:
model = Artist
fields = '__all__'
Unfortunately I think it isn't optimal solution and works only for hardcoded artist's id. I would like to get all artists and for ech list of other artists.
I was thinking about creating loop and iterate over Artist.objects.count() but I couldn't find a solid solution to maintain all this queries.
Is there any other, maybe easier way to solve this solution?
You can solve this issue from Serializer by using SerializerMethodField. Get all events in each Artist, the example below:
class ArtistSerializer(serializers.ModelSerializer):
class Meta:
model = Artist
fields = ('id', 'name', 'music_type', 'events')
events = serializers.SerializerMethodField()
def get_events(self, obj):
events_qs = Event.objects.filter(artists__in=[obj.id])
events = EventSerializer(
events_qs, many=True, context=self.context).data
return events
To avoid the error by the circle imports, you should use import in the function

Atrribute from nested relations is not read in serializer

I'm now using DRF as a backend of my project.
i have product model like this
class product(models.Model):
product_name = models.CharField(max_length=160)
i have category model like this
class category(models.Model):
category_name = models.CharField(max_length=60)
category_icon = models.ImageField(upload_to='category)
because 1 product can have multiple category and a lot of image I create
class product_category(models.Model):
product = models.ForeignKey(product, on_delete=models.CASCADE, related_name='product_collections')
category = models.ForeignKey(category, on_delete=models.CASCADE, related_name='category_collections')
and the last model
class product_image(models.Model):
product = models.ForeignKey(product, on_delete=models.CASCADE,related_name='image_collections')
product_img = models.ImageField(upload_to='product')
Now I have Serializer like this
class ProductCategorySerializer(serializers.ModelSerializer):
category_name = serializers.CharField(source='category.category_name')
class Meta:
model = product_category
fields = ('product_id','category_id','category_name')
class ProductImageSerializer(serializers.ModelSerializer):
class Meta:
model = product_images
fields = ('product_img',)
class ProductSerializer(serializers.ModelSerializer):
category_collections = CategoryProductSerializers(many=True)
image_collections = ProductImageSerializer(many=True)
class Meta:
model = product
fields = ('id','product_name','image_collections','category_collections')
From that serializer DRF will return
Error like this
Got AttributeError when attempting to get a value for field category_collections on serializer ProductSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the product instance.
but if i remove that category_collections field like this
class ProductSerializer(serializers.ModelSerializer):
# category_collections = CategoryProductSerializers(many=True)
image_collections = ProductImageSerializer(many=True)
class Meta:
model = product
fields = ('id','product_name','image_collections')
Everything is going fine, whats wrong with that categories collection, is my eye not seeing the mistake ?

Flask session not saving value/persisting across requests

bp = Blueprint('store', __name__)
#bp.route('/cart/<product_id>')
def add_to_cart(product_id):
print(session)
if "order_id" in session:
print(session["order_id"])
order = Order.query.get(session["order_id"])
# add products to order object ...
else:
order = Order()
db.session.add(order)
db.session.commit()
session["order_id"] = order.order_id
session.modified = True
return redirect(url_for('store.products'))
#bp.route('/', methods=['GET', 'POST'])
def products():
print(session)
When a user adds to cart the first time, I create a new order and save that order's order_id (an integer) in the session to add products to the order.
Then when they add to cart, I can query the Order and add products to it.
However, the session keeps resetting to an empty dictionary after the request to redirect to store.products page.
I'm not sure how to implement the session so that it persists across all requests and use it to keep track of the order_id.
My order table is defined as:
class Order(db.Model):
__tablename__ = 'Orders'
order_id = db.Column(db.Integer, primary_key=True)
products = db.relationship('Product', secondary=cart, back_populates='orders')
customer_id = db.Column(db.Integer, db.ForeignKey('Customers.customer_id'))
customer = db.relationship('Customer', back_populates='orders')
quantities = db.relationship('Quantity')
message = db.Column(db.Text)

How to save partial data in a separate model and then query checks if that data exists?

My data consists of some products, which are defined in FdProduct model:
# models.py:
class FdProduct(models.Model):
product_id = models.CharField(max_length=10, primary_key=True)
name = models.CharField(max_length=40)
active = models.BooleanField(default=True)
def __str__(self):
return self.product_id
# serializers.py:
class FdProductSerializer(serializers.ModelSerializer):
product_id = serializers.RegexField(regex='^\d{3}\.\d{6}$', max_length=10, min_length=10, allow_blank=False)
name = serializers.CharField(min_length=6, max_length=50, allow_blank=False)
class Meta:
model = FdProduct
fields = '__all__'
For each existing product I can prepare a configuration and save it using a model called SavedConfiguration:
# models:
class SavedConfiguration(models.Model):
saved_conf_id = models.CharField(max_length=13, primary_key=True)
saved_config = models.TextField()
product = models.ForeignKey(FdProduct, on_delete=models.CASCADE, default=0)
session_id = models.CharField(max_length=40, default=0)
creation_date = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
return str(self.saved_conf_id)
# serializers.py:
class SavedConfigurationSerializer(serializers.ModelSerializer):
saved_conf_id = serializers.RegexField(regex='^sc\d{2}', allow_blank=False)
saved_config = serializers.CharField(min_length=6)
session_id = serializers.RegexField(regex='^se\d{2}', allow_blank=False)
class Meta:
model = SavedConfiguration
fields = '__all__'
By connecting the SavedConfiguration with FdProduct model with use of ForeignKey I ensure that a product exists in the database when I configure it and want to save the configuration.
I'd like to introduce two things more: the first one would be a model for storing just a product_id and an array containing all saved_conf_ids for that product:
# models.py:
class ConfigOptions(models.Model):
product_id = ...
saved_conf_id = [...]
For example, if I configured a couple of times two products, Product One and Product Three, I may have data like this:
- Product One:
- C_ID_0023
- C_ID_0025
- C_ID_0032
- Product Three:
- C_ID_0149
- C_ID_0273
My question now is, how to construct such model and serializer for which records are created (copied) into ConfigOptions model table each time SavedConfiguration is saved?
Second question: I'm thinking about creating another model, say ConfigPresenceCheck, which would receive POST requests and based on that would check if saved product configurations exist (so, fetching them from ConfigOptions or returning 404), and if they exist, would return them together with all parameters from SavedConfiguration (e.g. saved_config, session_id, etc.).
Please give me directions how to build such models. I'd also appreciate some good tutorials related to
constructing Django models.
I think you should use many to many fields instead of foreign key, from my understanding many products can have many saved configurations and vice versa, at database level many to many fields are stored by creating a table any way.

How to search with django_tables2 when using filters

My problem is that I can not take back any data after filtering.
My search fields are : id name and surname. The two last taken from the Client which is foreign key.
filters.py
class OrderFilter(django_filters.FilterSet):
client__name = django_filters.CharFilter(lookup_expr='icontains')
client__surname = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = Order
fields = ['id']
models.py
class Order(models.Model):
client = models.ForeignKey(Client,verbose_name=u'Client')
tables.py
class OrderTable(tables.Table):
#CUSTOM COLUMN EXAMPLE
order_id=tables.Column(verbose_name= 'ID Order',orderable=False,empty_values=())
class Meta:
#define the model
model = Order
exclude=('id')
template_name = 'django_tables2/bootstrap.html'
sequence = ("order_id")
views.py
class OrderListView(SingleTableMixin,FilterView):
table_class = OrderTable
model = Order
template_name='orders/orde_list.html'
filterset_class = OrderFilter
def get_context_data(self, **kwargs):
context = super(OrderListView, self).get_context_data(**kwargs)
##filter the orders of the past 4 months.
last_four_months=date.today() - timedelta(120)
object_list=Order.objects.filter(order_created__gte=last_four_months,ays=1).order_by('-invoice_date')
table=self.table_class(object_list)
RequestConfig(self.request).configure(table)
context['table'] = table
#clear all fields
has_filter = any(field in self.request.GET for field in set(self.filterset_class.get_fields()))
context['has_filter'] = has_filter
return context
I noticed that when I create a custom queryset to fill my table, for ex: object_list=Order.objects.filter(order_created__gte=last_four_months).order_by('-invoice_date') the filtering is not working.
When I put nothing it works properly.
Any idea why this happening?
The issue was that I have not defined that my custom queryset must be inserted in the custom table(tables.py) and more important to be filtered by the custom filter (filters.py).
After doing that the custom queryset filtered correctly.
class OrderAYSListView(LoginRequiredMixin,SingleTableMixin,FilterView):
login_url = '/login/'
table_class = OrderTable2
model = Order
template_name='orders/order_ays_list.html'
filterset_class = OrderFilter
def get_context_data(self, **kwargs):
context = super(OrderAYSListView, self).get_context_data(**kwargs)
##filter the orders of the past 4 months.
last_four_months=date.today() - timedelta(120)
object_list=Order.objects.filter(order_created__gte=last_four_months,ays=1).order_by('-invoice_date')
f = self.filterset_class(self.request.GET, queryset=object_list)
context['filter'] = f
table = self.table_class(f.qs)
RequestConfig(self.request).configure(table)
context['table'] = table
#clear all fields
has_filter = any(field in self.request.GET for field in set(self.filterset_class.get_fields()))
context['has_filter'] = has_filter
return context

Resources