How can I create a model property based on specific model fields? - python

Let's say I have the following model:
class DriverReview(models.Model):
driver = models.ForeignKey(Driver, on_delete=models.CASCADE,)
driving_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)])
communication_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)])
professionalism_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)])
review_text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, related_name="driver_review_created_by", on_delete=models.CASCADE, null=True, blank=True)
last_updated = models.DateTimeField(auto_now=True)
last_updated_by = models.ForeignKey(User, related_name="driver_review_last_updated_by", on_delete=models.CASCADE, null=True, blank=True)
is_deleted = models.BooleanField(default=False)
deleted = models.DateTimeField(null=True, blank=True)
deleted_by = models.ForeignKey(User, related_name="driver_review_deleted_by", on_delete=models.CASCADE, null=True, blank=True)
#property
def review_average_score(self):
review_average_score = round(np.mean([self.driving_score, self.communication_score, self.professionalism_score]), 2)
return review_average_score
I have created a property to get the review average score. The issue is that I don't want to hardcode the _score fields. Is there a way to filter the fields that contain _score and use them in the average ?

Yes, you can inspect the fields through the _meta, so:
#property
def review_average_score(self):
data = [
getattr(self, f.attname)
for f in self._meta.get_fields()
if '_score' in f.name
]
review_average_score = np.mean(data), 2)
return review_average_score

Related

How to filter Many to Many field in django admin page using a foreign key value?

I am trying to filter my many to many variation fields with respect to the product. means, I only want the variations related to the current product to show in the admin page. now its showing all the variations available for every product.
I added formfield_for_manytomany() function to my admin.py but how can I get the current product(id) in the cart or order to filter the variations?
most of the questions in stack overflow Is based on the current user, which is easy to get? but how should I get the specific product(id) that is opened in the admin panel.
admin.py
from django.contrib import admin
from .models import *
from products.models import Variation
class CartAdmin(admin.ModelAdmin):
list_display = ('cart_id', 'date_created')
class CartItemAdmin(admin.ModelAdmin):
list_display = ('user','cart', 'product', 'quantity','is_active')
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "variation":
product = Products.objects.get(id='??') # how I get the current product in the cart or order
kwargs["queryset"] = Variation.objects.filter(product=product.id)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Cart, CartAdmin)
admin.site.register(CartItem, CartItemAdmin)
CartItem Model
class CartItem(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True)
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation = models.ManyToManyField(Variation, blank=True)
quantity = models.IntegerField()
is_active = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
def item_total(self):
return self.product.price * self.quantity
def __str__(self):
return self.product.name
Product and Variation Model
class Products(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = AutoSlugField(populate_from='name', max_length=100, unique=True)
isbn = models.CharField(max_length=20, unique=True, blank=True, null=True)
sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True)
author = models.CharField(max_length=100)
Publisher = models.CharField(max_length=100, blank=True, default=None)
release_date = models.DateField(blank=True, null=True, default=None)
price = models.IntegerField(default=None)
stock = models.IntegerField(default=None)
is_available = models.BooleanField(default=True)
cover_image = models.ImageField(upload_to='images/products')
image1 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image2 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image3 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
description = models.TextField(max_length=2000, blank=True, default=None)
create_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
number_of_pages = models.IntegerField(blank=True, null=True)
weight = models.IntegerField(blank=True, null=True)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
spine_width = models.IntegerField(blank=True, null=True)
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
def get_url(self):
return reverse('product-view', args=[self.slug])
def __str__(self):
return self.name
class Variation(models.Model):
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation_category = models.CharField(max_length=100, choices=variation_category_choice)
variation_value = models.CharField(max_length=100, choices=variation_value_choice)
is_available = models.BooleanField(default=True)
date_added = models.DateTimeField(auto_now_add=True)
objects = VariationManager()
def __str__(self):
return self.variation_value

While defining method for autosaving in CreateView for ManyToMany field Error shows

I have three Models, in third models Foreign Key and ManyToMany fields are linked, which are:
Personal_info Models.py
class Personal_info(models.Model):
gen_choices = (
("पुरुष", "पुरूष"),
("महिला", "महिला"),
("तेस्रो", "तेस्रो"),
)
pinfo_id = models.AutoField(primary_key=True)
userid = models.OneToOneField(User, on_delete=models.CASCADE)
nfullname = models.CharField(validators=[max_len_check], max_length=128)
efullname = models.CharField(validators=[max_len_check], max_length=128)
dob_ad = models.DateField()
dob_bs = models.DateField()
gender = models.CharField(max_length=6, choices=gen_choices)
citizen_no = models.CharField(max_length=56)
cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE)
cissue_date = models.DateField()
language = models.CharField(max_length=56)
p_district = models.CharField(max_length=56)
p_vdc = models.CharField(max_length=56)
p_ward = models.CharField(max_length=2)
p_city = models.CharField(max_length=56)
t_district = models.CharField(max_length=56)
t_vdc = models.CharField(max_length=59)
t_ward = models.CharField(max_length=2)
t_city = models.CharField(max_length=56)
telephone = models.BigIntegerField(null=True, blank=True)
mobile = models.BigIntegerField()
mother_name = models.CharField(validators=[max_len_check], max_length=128)
mother_cit = models.CharField(max_length=10, null=True)
father_name = models.CharField(validators=[max_len_check], max_length=128)
father_cit = models.CharField(max_length=10, null=True)
gfather_name = models.CharField(validators=[max_len_check], max_length=128)
gfather_cit = models.CharField(max_length=10, null=True)
spose_name = models.CharField(validators=[max_len_check], max_length=128, null=True)
spose_cit = models.CharField(max_length=10, null=True, blank=True)
image = models.FileField(upload_to="photos/", null=True, blank=True)
cit_image = models.FileField(upload_to="citizens/")
inclu_image = models.FileField(upload_to="inclusions/", null=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.efullname)
Educational Models.py
class Education(models.Model):
edu_id = models.AutoField(primary_key=True)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
institute = models.CharField(max_length=255, validators=[max_len_check])
board = models.CharField(max_length=128, validators=[max_len_check1])
pexam = models.CharField(max_length=16, choices=exam_choices)
faculty = models.CharField(max_length=16, choices=fac_choices)
division = models.CharField(max_length=16, validators=[max_len_check2])
tmarks = models.IntegerField()
percent = models.FloatField(null=True, blank=True)
mainsub = models.CharField(max_length=16, validators=[max_len_check2])
image = models.FileField(upload_to="educations/", null=True, blank=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.userid)
V_applied models.py
class V_applied(models.Model):
appNo = models.IntegerField(null=True, blank=True, default=add_one)
p_srlno = models.IntegerField(blank=True, null=0, default=0)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Vacancy,on_delete=models.CASCADE)
inclusive = models.ManyToManyField(Inclusive)
bank = models.CharField(max_length=128)
v_no = models.CharField(max_length=32, validators=[max_len_check1])
dep_date = models.DateField()
ser_fee = models.IntegerField()
image = models.FileField(upload_to="vouchers/")
personal_info = models.ForeignKey(Personal_info, on_delete=models.CASCADE, blank=True)
education = models.ManyToManyField(Education, blank=True, default=0)
active = models.BooleanField(default=True)
status = models.CharField(max_length=10, validators=[max_len_check], default="Pending")
remarks = models.CharField(max_length=56, validators=[max_len_check1], default="Pending")
comment = models.CharField(max_length=128, validators=[max_len_check2], blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
#property
def per_info(self):
return (self.personal_info.efullname, self.personal_info.gender, )
'''
def __str__(self):
return str(self.userid) + ':' + str(self.post)
Here I want to make auto save method in CreateView for ForeignKey & ManyToMany fields of V_applied models, for this I tried views.py as below:
#method_decorator(login_required(login_url='login'), name='dispatch')
class v_appliedadd(CreateView):
form_class = V_appliedForm
template_name = 'v_applied/v_applied_form.html'
success_url = '/v_applied/vapp_details/'
def form_valid(self, form):
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
form.instance.education.add(edu)
return super().form_valid(form)
While saving data Error display like this:
ValueError at /v_applied/v_appliedadd/
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Request Method: POST
Request URL: http://localhost:8000/v_applied/v_appliedadd/
Django Version: 3.0.8
Exception Type: ValueError
Exception Value:
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py in __init__, line 846
Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.1
Python Path:
['D:\\DjangoProject\\app_epf',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\User\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Mon, 14 Sep 2020 23:09:21 +0545
I am new in python-django, please help me how to solve it.
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
instance_from = form.save()
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
instance_edu = Education.objects.get(pk=edu.pk)
instance_from.education.add(instance_edu)
instance_from.save()
return super().form_valid(form)

Is this possible? Using signals to set a global variable

I have made this function that runs every time a user logs in. I want to get the branch from 'user' but every time the session is set it's only available to the function even after setting it to BRANCH_ID in the settings file. any help? plus I don't want to do anything in view function with the request as it's not accessible from models
EDIT
I have added all the models
def perform_some_action_on_login(sender, request, user, **kwargs):
"""
A signal receiver which performs some actions for
the user logging in.
"""
request.session[settings.BRANCH_ID] = user.profile.branch_id
branch = request.session.get(settings.BRANCH_ID)
print(branch)
user_logged_in.connect(perform_some_action_on_login)
class WaybillTabularInlineAdmin(admin.TabularInline):
model = WaybillItem
extra = 0
# form = WaybillItemForm
fk_name = 'waybill'
autocomplete_fields = ('product',)
class WaybillAdmin(admin.ModelAdmin):
list_display = (
'from_branch',
'to_branch',
'updated_by',
)
list_filters = (
'from_branch',
'to_branch',
'product',
)
inlines = [WaybillTabularInlineAdmin]
readonly_fields = ("updated_by",)
what I was trying to do is products by the branch
class Waybill(models.Model):
from_branch = models.ForeignKey(
Branch,
default=1,
on_delete=models.CASCADE, related_name='from_branch')
to_branch = models.ForeignKey(
Branch, on_delete=models.CASCADE, related_name='to_branch')
comments = models.CharField(max_length=1024, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(
User, on_delete=models.CASCADE,
blank=True, null=True,
related_name='waybill_created')
updated = models.BooleanField(default=False)
updated_by = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='waybill_user')
def __str__(self):
return 'from {} to {}'.format(
self.from_branch.branch_name,
self.to_branch.branch_name,
)
class WaybillItem(models.Model):
waybill = models.ForeignKey(Waybill, on_delete=models.CASCADE)
product = models.ForeignKey(ProductDetail, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
def __str__(self):
return 'from {} to {}'.format(
self.waybill.from_branch,
self.waybill.to_branch
)
class Product(models.Model):
item = models.ForeignKey(
Item, on_delete=models.CASCADE, related_name="product")
branch = models.ForeignKey(
Branch, default=1, on_delete=models.CASCADE)
in_stock = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
objects = ProductManager()
class Meta:
verbose_name = "Inventory"
verbose_name_plural = "Inventories"
ordering = ("-created_date",)
constraints = [
models.UniqueConstraint(
fields=['item', 'branch'], name='unique product'),
]
def __str__(self):
return self.item.item_description
class ProductDetail(models.Model):
ITEM_CONDITION_CHOICES = (
("NEW", "New"),
("BROKEN", "Broken"),
("FAIRLY USED", "Fairly Used"),
)
condition = models.CharField(max_length=12, choices=ITEM_CONDITION_CHOICES,
default=ITEM_CONDITION_CHOICES[0][0])
product = models.ForeignKey(Product, on_delete=models.CASCADE)
short_description = models.CharField(max_length=255, blank=True)
color = models.CharField(max_length=15, blank=True)
bought_price = models.PositiveIntegerField(default=0.00)
sales_price = models.PositiveIntegerField(default=0.00)
retail_price = models.PositiveIntegerField(default=0.00)
item_code = models.CharField(max_length=15, default=0)
item_model_number = models.CharField(max_length=20, default=0)
quantity = models.PositiveIntegerField(default=0)
manufacturer_website = models.CharField(max_length=255, blank=True)
generated_url = models.CharField(max_length=255, blank=True)
created_date = models.DateTimeField(default=timezone.now)
updated_date = models.DateTimeField(auto_now=True)
# objects = ProductDetailManager()

Django Restful_Api post Json for more than one record in a time

I use Django Restful Api ,I want to post records(more than one record!) in a time ,Models ,serialize,viewset are as follows
Does anyone has some advice? thanks advcance!
model
class Brand(models.Model):
Company_Group = models.ManyToManyField(Company)
Brand_Group = models.CharField(u'Brand Group',max_length=255, default="")
Pref_Brand_Name_Flg = models.CharField(u'Preferred Brand Name Flag',max_length=255, default="")
Pref_Brand_Name = models.CharField(u'Preferred Brand Name',max_length=255, default="")
PrimaryContact = models.ForeignKey(UserRole, null=True, blank=True) #primarybroker
Protect_period = models.CharField(u'Protect period',max_length=255, default="")
# Pref_Brand_Name = models.CharField(u'Preferred Brand Name',max_length=255, default="")
Brand_Name = models.CharField(u'Brand Name',max_length=255, default="")
Brand_Name_SC = models.CharField(u'Brand Name in Local Language',max_length=255, default="")
Year_Enter_Market = models.CharField(u'Entered Market in (Year)',max_length=255, default="")
Category_Display = models.CharField(u'Category Display',max_length=255, default="")
Category_1_Code = models.CharField(u'Category',max_length=255, default="")
Category_2_Code = models.CharField(u'Sub Category',max_length=255, default="")
Price_Low = models.CharField(u'Price Range - Low',max_length=255, default="")
Price_High = models.CharField(u'Price Range - High',max_length=255, default="")
Size_Low = models.CharField(u'Typical Store Size - Low',max_length=255, default="")
Size_High = models.CharField(u'Typical Store Size - High',max_length=255, default="")
Headerquater = models.CharField(u'Headerquater',max_length=255, default="")
Status = models.CharField(u'Status',max_length=255, default="")
Created_On = models.DateField(u'Created On',auto_now_add=True)
Created_By = models.CharField(u'Created By',max_length=255, default="")
Modified_On = models.DateField(u'Modified On', auto_now=True)
Modified_By = models.CharField(u'Modified By',max_length=255, default="")
Agreement_InPlace_Flg = models.CharField(u'TR Agreement in place?',max_length=20, default="")
Web_Site = models.CharField(u'Web Site',max_length=20, default="")
Comment = models.CharField(u'Comment',max_length=20, default="")
viewset
class BrandViewSet(viewsets.ModelViewSet):
queryset = Brand.objects.all()
serializer_class = BrandSerializer
Serializer
class BrandSerializer(serializers.HyperlinkedModelSerializer):
PrimaryContact_id = serializers.ReadOnlyField(source='PrimaryContact.id', read_only=True)
def __init__(self, *args, **kwargs):
many = kwargs.pop('many', True)
super(BrandSerializer, self).__init__(many=many, *args, **kwargs)
class Meta:
model = Brand
fields = data_export_setting.Brand_form_stand # +options ??
#Brand_detail = serializers
"myTest code" :a.py
item = [{"id":"2","PrimaryContact_id":"00000","Pref_Brand_Name_Flg":"00000","Protect_period":"test_for_Protect_period_1","Pref_Brand_Name":"Test","Brand_Name":"Chanel Group","Brand_Name_SC":"test","Year_Enter_Market":"test","Category_Display":"test","Category_1_Code":"api","Category_2_Code":"api","Price_Low":"test","Price_High":"test","Size_High":"test","Headerquater":"test","Status":"test","Created_On":"2017-06-14","Modified_By":"2017-07-08","Modified_On":"000"},{"id":"3","PrimaryContact_id":"1111","Pref_Brand_Name_Flg":"11111","Protect_period":"ppppp","Pref_Brand_Name":"Test","Brand_Name":"Chanel Group 2","Brand_Name_SC":"test","Year_Enter_Market":"test","Category_Display":"test","Category_1_Code":"api","Category_2_Code":"api","Price_Low":"test","Price_High":"test","Size_High":"test","Headerquater":"test","Status":"test","Created_On":"2017-06-14","Modified_By":"2017-07-08","Modified_On":"000"}]
data=json.dumps(item)
def test_get_user_list_3():
resp = requests.post(urlname,auth=AUTH,data=data,headers={ "Content-Type":"application/json","Accept": "application/json"})
test_get_user_list_3()
if item as for one record ,it works
item ={"id":"1","PrimaryContact_id":"00000","Pref_Brand_Name_Flg":"00000","Protect_period":"test_for_Protect_period_1","Pref_Brand_Name":"Test","Brand_Name":"Chanel Group","Brand_Name_SC":"test","Year_Enter_Market":"test","Category_Display":"test","Category_1_Code":"api","Category_2_Code":"api","Price_Low":"test","Price_High":"test","Size_High":"test",Headerquater":"test","Status":"test","Created_On":"2017-06-14","Modified_By":"2017-07-08","Modified_On":"000"},
Ok, i've spent a considerable amount of time trying to get this work. Below is the code that i've used to get this to do bulk creates.
The get_serializer method that's used by default for ModelViewSet passes in the data without many=True so you have to override it and make sure you check the request for a list instead of a dictionary.
That's the only change required to be able to bulk create items from a list.
models.py
class Brand(models.Model):
# ------------------------------------------
# Relations
# ------------------------------------------
Company_Group = models.ManyToManyField(Company)
PrimaryContact = models.ForeignKey(User, null=True, blank=True)
# ------------------------------------------
# Attributes
# ------------------------------------------
# Brand attrs
Brand_Name = models.CharField(u'Brand Name',max_length=255, blank=True)
Brand_Group = models.CharField(u'Brand Group',max_length=255, blank=True)
Pref_Brand_Name = models.CharField(u'Preferred Brand Name',max_length=255, blank=True)
Brand_Name_SC = models.CharField(u'Brand Name in Local Language',max_length=255, blank=True)
Pref_Brand_Name_Flg = models.CharField(u'Preferred Brand Name Flag',max_length=255, blank=True)
# Record management attrs
Modified_On = models.DateField(u'Modified On', auto_now=True)
Created_On = models.DateField(u'Created On', auto_now_add=True)
Created_By = models.CharField(u'Created By', max_length=255, blank=True)
Modified_By = models.CharField(u'Modified By', max_length=255, blank=True)
# Category attrs
Category_1_Code = models.CharField(u'Category', max_length=255, blank=True)
Category_2_Code = models.CharField(u'Sub Category', max_length=255, blank=True)
Category_Display = models.CharField(u'Category Display',max_length=255, blank=True)
# Pricing attrs
Price_Low = models.CharField(u'Price Range - Low', max_length=255, blank=True)
Price_High = models.CharField(u'Price Range - High', max_length=255, blank=True)
# Store attrs
Size_Low = models.CharField(u'Typical Store Size - Low', max_length=255, blank=True)
Size_High = models.CharField(u'Typical Store Size - High', max_length=255, blank=True)
# Company attrs
Status = models.CharField(u'Status', max_length=255, blank=True)
Comment = models.CharField(u'Comment', max_length=20, blank=True)
Web_Site = models.CharField(u'Web Site', max_length=20, blank=True)
Headerquater = models.CharField(u'Headerquater', max_length=255, blank=True)
Protect_period = models.CharField(u'Protect period', max_length=255, blank=True)
Year_Enter_Market = models.CharField(u'Entered Market in (Year)', max_length=255, blank=True)
Agreement_InPlace_Flg = models.CharField(u'TR Agreement in place?', max_length=20, blank=True)
def __str__(self):
return self.Brand_Name
class Meta:
db_table = 'brand'
serializers.py
class BrandSerializer(serializers.ModelSerializer):
class Meta:
model = Brand
fields = '__all__'
views.py
class BrandViewSet(viewsets.ModelViewSet):
model = Brand
serializer_class = BrandSerializer
queryset = Brand.objects.all()
def get_serializer(self, *args, **kwargs):
if 'data' in kwargs:
data = kwargs['data']
if isinstance(data, list):
kwargs['many'] = True
return super().get_serializer(*args, **kwargs)
urls.py
from rest_framework.routers import DefaultRouter
from .views import BrandViewSet
router = DefaultRouter()
router.register(r'brand', BrandViewSet)
urlpatterns = router.urls
I sent the data(JSON) using postman in this format:
[
{
"Brand_Name":"",
"Brand_Group":"",
"Pref_Brand_Name":"",
"Brand_Name_SC":"",
"Pref_Brand_Name_Flg":"",
"Created_By":"",
"Modified_By":"",
"Category_1_Code":"",
"Category_2_Code":"",
"Category_Display":"",
"Price_Low":"",
"Price_High":"",
"Size_Low":"",
"Size_High":"",
"Status":"",
"Comment":"",
"Web_Site":"",
"Headerquater":"",
"Protect_period":"",
"Year_Enter_Market":"",
"Agreement_InPlace_Flg":"",
"PrimaryContact":null,
"Company_Group":[
1
]
},
{
"Brand_Name":"",
"Brand_Group":"",
"Pref_Brand_Name":"",
"Brand_Name_SC":"",
"Pref_Brand_Name_Flg":"",
"Created_By":"",
"Modified_By":"",
"Category_1_Code":"",
"Category_2_Code":"",
"Category_Display":"",
"Price_Low":"",
"Price_High":"",
"Size_Low":"",
"Size_High":"",
"Status":"",
"Comment":"",
"Web_Site":"",
"Headerquater":"",
"Protect_period":"",
"Year_Enter_Market":"",
"Agreement_InPlace_Flg":"",
"PrimaryContact":null,
"Company_Group":[
1
]
}
]
As shown in DRF documentation you can utilize the ListSerializer to create multiple instances of the model.
Your best bet is to create a separate serializer(ListSerializer) with an your own custom .create() method for creating multiple instances of your model. Then in your view you write some business logic to check if it's a single object or a list of multiple objects and send them to the appropriate serializer for creation. Make sure you take a look at the ListSerializer and how to use many=True.
You can potentially use the same serializer with your own custom .create() method and have the business logic inside of there but look at the documentation and see the recommended way of creating multiple instances of objects.

import m2m with Django-import-export failing

Data import using django-import-export is failing for m2m relationships.
The transaction doesn't generate any errors, however when trying to update an object's m2m relationship none of the updated values for m2m are being updated.
models.py
class Category(MPTTModel):
name = models.CharField(max_length=155, verbose_name=_('Category'))
code = models.CharField(max_length=255, verbose_name=_('Category Code'), help_text='primary key value for category', db_index=True)
categorytype = models.ForeignKey(ProductType, related_name='categories_for', verbose_name=_('Product type'), blank=True, null=True)
meta_description = models.TextField(verbose_name=_('Meta Description'))
meta_keywords = models.TextField(verbose_name=_('Meta Keywords'))
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
slug = models.SlugField(blank=True, verbose_name=_('URL alias'))
order = models.PositiveIntegerField()
class Product(models.Model):
reference = models.CharField(max_length=50, verbose_name=_('Reference'), db_index=True)
name = models.CharField(max_length=255, verbose_name=_('Product Name'))
description = models.TextField(blank=True, verbose_name=_('Product Description'))
specs = models.TextField(blank=True, verbose_name=_('Product Specifications'))
color_code = models.ForeignKey(ColorCode, verbose_name=_('Color Code'), related_name='colorcode_for')
color_web = models.CharField(max_length=7, verbose_name=_('Web Color'), db_index=True)
size = models.CharField(max_length=11, verbose_name=_('Product Size'))
price = models.IntegerField(verbose_name=_('Product Price'))
price_promo = models.IntegerField(blank=True, null=True, verbose_name=_('Product Promo Price'))
upc = models.CharField(max_length=155, verbose_name=_('UPC'))
stock = models.IntegerField(verbose_name=_('Product Stock'))
categories = models.ManyToManyField(Category, verbose_name=_('Estilo'), related_name='products')
in_stores = models.BooleanField(default=True, verbose_name=_('Product Availability'), db_index=True)
try_out = models.BooleanField(default=False, verbose_name=_('Try out Product'))
pub_date = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
slug = models.SlugField(default='', blank=True, verbose_name=_('URL alias'))
blog = models.URLField(blank=True, verbose_name=_('Blog mention link'))
parent_product = models.BooleanField(default=False, verbose_name=_('Main Product'), db_index=True)
main_product = models.ForeignKey('Product', blank=True, null=True, related_name='child_product')
active = models.BooleanField(default=True, verbose_name=_('Active'), db_index=True)
trends = models.ManyToManyField(Trends, verbose_name=_('Trends'), blank=True, related_name="trends")
photoshoot_id = models.CharField(max_length=255, verbose_name=_('Photoshoot ID'), blank=True)
new_arrival = models.BooleanField(default=False, db_index=True)
resources.py
class ProductResource(resources.ModelResource):
categories = fields.Field(widget=widgets.ManyToManyWidget(Category, separator="/"))
def export(self, queryset=None):
queryset = Product.objects.all()
headers = self.get_export_headers()
data = tablib.Dataset(headers=headers)
for obj in queryset.iterator():
data.append(self.export_resource(obj))
return data
class Meta:
model = Product
fields = ('categories', 'reference', 'name_es', 'name_en', 'description_es', 'description_en', 'specs_es', 'specs_en', 'color_code', 'color_web', 'size', 'price_es', 'price_en', 'price_promo_es', 'price_promo_en', 'upc', 'stock', 'in_stores', 'try_out', 'blog', 'active', 'photoshoot_id')
import_id_fields = ['upc']
skip_unchanged = True
Issue was fixed removing the skip_unchanged meta option, the skip_rowmethod in the ModelResource class is not reading the new value assigned in the .CSV

Categories

Resources