Django select only models with different field - django

I have a model called Product_Variation:
class Product_Variation( models.Model ):
color = models.ForeignKey('Color', verbose_name="Color", on_delete=models.CASCADE, null=True, blank=True)
size = models.ForeignKey('Size', verbose_name="Size", on_delete=models.CASCADE, null=True, blank=True)
sku = models.CharField(verbose_name="SKU", max_length=255, null=True, blank=True)
main_picture = FilerImageField(related_name="main_picture", verbose_name="Main Picture", null=True, blank=True)
image_gallery = models.ManyToManyField('Media', related_name="image_gallery", verbose_name="Image Gallery", blank=True)
regular_price = models.FloatField(verbose_name="Regular Price", null=True, blank=True)
sale_price = models.FloatField(verbose_name="Sale Price", null=True, blank=True)
stock_quantity = models.PositiveIntegerField(verbose_name="Stock Quantity", default=0, null=True, blank=True)
weight = models.FloatField(verbose_name="Weight", default=0, null=True, blank=True)
dimension_length = models.FloatField(verbose_name="Length", default=0, null=True, blank=True)
dimension_width = models.FloatField(verbose_name="Width", default=0, null=True, blank=True)
dimension_height = models.FloatField(verbose_name="Height", default=0, null=True, blank=True)
barcode = models.CharField(verbose_name="Barcode", max_length=255, null=True, blank=True)
priority = models.PositiveIntegerField(verbose_name="Priority", null=True, blank=True)
total_view = models.PositiveIntegerField(verbose_name="Total View", default=0, null=True, blank=True)
total_sales = models.PositiveIntegerField(verbose_name="Total Sales", default=0, null=True, blank=True)
created = models.DateTimeField(default=now)
product = models.ForeignKey('Product', verbose_name="Product that Variation belongs to", on_delete=models.CASCADE, null=True, blank=True)
How do i get Product_variations that have distinct color? I am using mysql.
I tried:
Product_Variation.objects.all().values('product__id', 'color').distinct()
but i don't know how to get only the id too, because if i use
Product_Variation.objects.all().values('id', 'product__id', 'color').distinct()
the distinct does not work anymore because the id are all unique

Something like this:
distinct_prod_vars = Product_Variation.objects.all().distinct('color')

try this:
distinct_prod_vals = Product_Variation.objects.values('color').distinct()

Related

It is not possible to migrate a new user element to the django table

I am faced with the problem that it is not possible to migrate the new user value to the database table. At first there were errors on related_name, but I fixed it, and now that this value cannot be zero, at the same time, if I write that null=True, then the user cannot be displayed in the records in the future.
class Writehelp(models.Model):
users = models.ForeignKey(User,on_delete = models.CASCADE,related_name='helpedman',null=False,verbose_name='Автор')
titles = models.CharField(max_length=200, verbose_name='Заголовок', blank=True)
descriptions = models.TextField(blank=True, verbose_name='Описание')
createdtimes = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания')
prices = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена')
course = models.IntegerField(null=True, blank=True, verbose_name='Курс')
semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр')
subjects = models.CharField(max_length=200, null=True, blank=True, verbose_name='Предмет')
institutes = models.CharField(max_length=200, null=True, blank=True, verbose_name='Институт')
However, when I migrated this model, there were no problems:
class UploadFile(models.Model):
user = models.ForeignKey(User,on_delete = models.CASCADE,related_name='file_created' ,verbose_name='Автор')
title = models.CharField(max_length=200, verbose_name='Заголовок',blank=True)
# uploadedfile = models.FileField(upload_to='files/',null=True, verbose_name='Файл')
description = models.TextField(blank=True, verbose_name='Описание')
createdtime = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания')
price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена')
number_course = models.IntegerField(null=True, blank=True, verbose_name='Курс')
number_semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр')
subjectt = models.CharField(max_length=200, null=True,blank=True,verbose_name='Предмет')
type_materials = models.CharField(max_length=200,null=True,blank=True, verbose_name='Тип работы')
institute = models.CharField(max_length=200, null=True,blank=True, verbose_name='Институт')
Add defult=None to uploadedfile field in your UploadFile model.

Cannot resolve keyword annotated field django

this is my model
class ExchangeReportTime(models.Model):
creator = models.ForeignKey('accounts.Account', on_delete=models.CASCADE, null=True, verbose_name=_('Creator'))
create_time = models.DateTimeField(default=timezone.now)
exchange = models.ForeignKey(BorseExchange, on_delete=models.SET_NULL, null=True,
related_name='report_times')
actual_fiscal_month = models.CharField(max_length=255, null=True, blank=True)
fiscal_month = models.CharField(max_length=5, null=True, blank=True)
fiscal_year = models.CharField(max_length=255, null=True, blank=True)
is_fiscal_year_changed = models.BooleanField(null=True, blank=True)
period_ending_date = models.CharField(max_length=15, null=True, blank=True)
statement_key = models.IntegerField(null=True, blank=True)
statement_type = models.CharField(max_length=50, null=True, blank=True)
...
fiscal_month and fiscal_year are string so i change types and query as below
exchange = BorseExchange.objects.get(tse_code=exchange_number)
last_12_season = exchange.report_times.filter(
statement_type='InterimIncomeStatement',
period_type='seasonally'
).annotate(
fiscal_month_number=Cast('fiscal_month',IntegerField()),
fiscal_year_number=Cast('fiscal_year',IntegerField()),
).order_by(
'-fiscal_year_number', '-fiscal_month_number'
).distinct(
'fiscal_month_number', 'fiscal_year_number'
)[:records_count]
print(last_12_season.values_list('id'))
but i give error:
django.core.exceptions.FieldError: Cannot resolve keyword 'fiscal_month_number' into field. Choices are: actual_fiscal_month, attachment_url, auditing, company_key, create_time, creator, creator_id, currency, exchange, exchange_id, fiscal_month, fiscal_year, html_url, id, is_empty, is_fiscal_year_changed, period_ending_date, period_type, publish_date, publish_time, report_items, scenario, statement_key, statement_type
where is the problem?
python3.6 and django 2.2.*

FOREIGN KEY constraint failed in signals

I tried to insert data into the table Account, but I keep getting this error message.
I delete all my migrations and make migrations again but I keep getting this error.
Here is my models.
class Student(models.Model):
user = models.OneToOneField(Account, on_delete=models.CASCADE)
name = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=15, blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True, null=True)
section = models.ForeignKey(Section, on_delete=models.CASCADE, default=1)
dept = models.ForeignKey(Dept, on_delete=models.CASCADE, blank=True, null=True)
batch = models.CharField(max_length=15, null=True, blank=True)
USN = models.CharField(primary_key='True', max_length=100)
DOB = models.DateField(default='1998-01-01')
profile_image = models.ImageField(upload_to='student/profile_images/%Y/%m/%d/', blank=True, null=True)
address = models.CharField(max_length=300, null=True, blank=True)
nationality = models.CharField(max_length=100, null=True, blank=True)
guardian_name = models.CharField(max_length=200, null=True, blank=True)
guardian_number = models.CharField(max_length=15, null=True, blank=True)
guardian_address = models.CharField(max_length=300, null=True, blank=True)
blood_group = models.CharField(max_length=3, null=True, blank=True)
exam_name = models.CharField(max_length=300, null=True, blank=True)
background = models.CharField(max_length=300, null=True, blank=True)
passing_year = models.CharField(max_length=8, null=True, blank=True)
score = models.CharField(max_length=10, null=True, blank=True)
school_name = models.CharField(max_length=300, null=True, blank=True)
country = models.CharField(max_length=100, null=True, blank=True)
certificate = models.FileField(upload_to='certificates/%Y/%m/%d/', null=True, blank=True)
Here is Account model.
class Account(AbstractBaseUser, PermissionsMixin):
unid = models.CharField(max_length=20, unique=True, null=True, blank=True)
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True)
user_permissions = models.ManyToManyField(
Permission,
verbose_name=_('user permissions'),
blank=True,
null=True,
help_text=_('Specific permissions for this user.'),
related_name="user_set",
related_query_name="user",
)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
registered = models.BooleanField(default=False)
so what I did is that when I create account if the is_student is True I create a signals that going to create student model for that account instance automatically.
here is the signals
def create_student_or_teacher(sender, created, instance, **kwargs):
if created:
if instance.is_student:
Student.objects.create(
user=instance,
USN=instance.unid,
)
elif instance.is_teacher:
Teacher.objects.create(
user=instance,
id=instance.unid,
)
So when I create the account for student the tracker will highlight in the signals Student.objects.create(...)
If you have any idea I hope it would help me.
UPDATED:
When I'm creating teacher it is working find.
here is the teacher model
class Teacher(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=15, blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True)
salary = models.IntegerField(default=1)
school = models.ForeignKey(School, blank=True, null=True, on_delete=models.CASCADE)
section = models.ForeignKey(Section, blank=True, null=True, on_delete=models.CASCADE)
user = models.OneToOneField(Account, on_delete=models.CASCADE, null=True)
id = models.CharField(primary_key=True, max_length=100)
dept = models.ForeignKey(Dept, on_delete=models.CASCADE, blank=True, null=True)
DOB = models.DateField(default='1980-01-01')
profile_image = models.ImageField(upload_to='teacher/profile_images/%Y/%m/%d/', blank=True, null=True)
nationality = models.CharField(max_length=300, null=True, blank=True)
address = models.CharField(max_length=300, null=True, blank=True)
Finally after few hours I solved my error it was simple
in the section I set default value which was not exist
so I just change the value to an exist one and that was it.

Improving performance of an Django MPTT tree

I have implemented the follow model to capture the structure of a classical piece of music. I'm using the MPTT to implement movements, opera acts and arias.
model.py:
TreeForeignKey(Work, blank=True, null=True, db_index=True, on_delete=models.PROTECT).contribute_to_class(Work, 'parent')
mptt.register(Work, order_insertion_by=['id'])
class Work(models.Model):
attributed_to = models.NullBooleanField()
name = models.CharField(max_length=400, null=True, blank=True)
lang = models.CharField(max_length=2, null=True, blank=True)
name_original = models.CharField(max_length=200, null=True, blank=True)
lang_original = models.CharField(max_length=2, null=True, blank=True)
name_common = models.CharField(max_length=200, null=True, blank=True)
name_common_orig = models.CharField(max_length=200, null=True, blank=True)
dedicated_to = models.CharField(max_length=200, null=True, blank=True)
pic = models.ImageField(upload_to = 'pic_folder/', default = '/pic_folder/None/no-img.jpg')
piece_type = models.CharField(max_length=100, null=True, blank=True)
category = models.CharField(max_length=100, null=True, blank=True)
date_start = models.CharField(max_length=100, null=True, blank=True)
date_start_gran = models.CharField(max_length=5, choices=DATE_TYPES, default='Year')
date_signature = models.CharField(max_length=100, null=True, blank=True)
date_signature_gran = models.CharField(max_length=10, choices=DATE_TYPES, default='Year')
around = models.BooleanField(null=True)
date_published = models.CharField(max_length=100, null=True, blank=True)
date_published_gran = models.CharField(max_length=10, choices=DATE_TYPES, default='Year')
desc = models.TextField(max_length=8000, null=True, blank=True)
order = models.CharField(max_length=100, null=True, blank=True)
class Work_Music(Work):
composer = models.ForeignKey(Composer, verbose_name=_('composer'), null=True, blank=True, on_delete=models.PROTECT)
key = models.CharField(max_length=10, null=True, blank=True)
tonality = models.CharField(max_length=20, null=True, blank=True)
Here is the view.py:
class ComposerOverviewView(TemplateView):
template_name = 'composers/overview/catalogue.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
opus = Work_Music.objects.filter(composer=self.kwargs['pk'], level=0)
context.update({
'composer': Composer.objects.get(pk=self.kwargs['pk']),
'opus': opus,
})
return context
When I try to run a query for all of the works for a composer (in the DB there are a total of 264 works), the queryset take almost 6 secs to run. I was wondering if anyone knows how to improve my code to increase the performance. There seems to be some with the delay_mptt_updates() method. But I'm not sure where it would go in my code.
I read in another article that MPTT sometimes does run slow. If I can increase the performance, what are some other alternatives?

Django Nested Serializer does not find attribute

This are my models
class OWNER_STORE(models.Model):
_id = models.CharField(max_length=120, unique=True, default=uuid.uuid4)
MSE_STORE_TYPE = models.ForeignKey(STORE_TYPE)
MSE_OWNER_INFO = models.ForeignKey(OWNER_INFO, related_name='STORES')
STORE_NAME = models.CharField("STORE_NAME", max_length=250, null=True, blank=True)
STORE_ID = models.IntegerField("STORE_ID", null=True, blank=True)
STORE_ADDRESS_HOUSE = models.CharField("STORE_ADDRESS_HOUSE", max_length=250, null=True, blank=True)
STORE_ADDRESS_ROAD = models.CharField("STORE_ADDRESS_ROAD", max_length=250, null=True, blank=True)
STORE_ADDRESS_VILLAGE = models.CharField("STORE_ADDRESS_VILLAGE", max_length=250, null=True, blank=True)
STORE_ADDRESS_UNION = models.CharField("STORE_ADDRESS_UNION", max_length=250, null=True, blank=True)
STORE_ADDRESS_THANA = models.CharField("STORE_ADDRESS_THANA", max_length=250, null=True, blank=True)
STORE_ADDRESS_DISTRICT = models.CharField("STORE_ADDRESS_DISTRICT", max_length=250, null=True, blank=True)
STORE_ADDRESS_DIVISION = models.CharField("STORE_ADDRESS_DIVISION", max_length=250, null=True, blank=True)
STORE_EMPLOYEE_STATUS = models.BooleanField("EMPLOYEE_STATUS")
STORE_NUMBER_OF_EMPLOYEE = models.IntegerField("NUMBER_OF_EMPLOYEE", null=True, blank=True)
STORE_AVG_REVENUE = models.IntegerField("STORE_AVG_REVENUE", null=True, blank=True)
STORE_AVG_COGS = models.IntegerField("STORE_AVG_COGS", null=True, blank=True)
STORE_AVG_PROFIT = models.IntegerField("STORE_AVG_PROFIT", null=True, blank=True)
STORE_CUSTOMER_CREDIT_LIMIT = models.IntegerField("CUSTOMER_CREDIT_LIMIT", null=True, blank=True)
STORE_BUSINESS_TARGET = models.IntegerField("BUSINESS_TARGET", null=True, blank=True)
STORE_REORDER_THRESHOLD = models.IntegerField("REORDER_THRESHOLD", null=True, blank=True)
STORE_PASSWORD = models.TextField("STORE_PASSWORD", max_length=50, default=None, null=True, blank=True)
def __str__(self):
return str(self.id)
class MSE_EMPLOYEE(models.Model):
emp_id = models.IntegerField(null=True, blank=True)
store = models.ForeignKey(OWNER_STORE)
MSE_EMPLOYEE_ID = models.IntegerField(null=True, blank=True)
MSE_EMPLOYEE_NAME=models.CharField(max_length=250, null=True, blank=True)
MSE_EMPLOYEE_MOBILE_NUMBER = models.CharField(max_length=250, null=True, blank=True)
MSE_EMPLOYEE_JOINING_DATE = models.DateField(null=True, blank=True)
MSE_EMPLOYEE_SALARY = models.IntegerField(null=True, blank=True)
def __str__(self):
return str(self.MSE_EMPLOYEE_NAME)
For my serializers.py, I did this
class STORE_EMPLOYEE_SERIALIZER(serializers.ModelSerializer):
employees = EMPLOYEE_SERIALIZER(many=True)
class Meta:
model = OWNER_STORE
fields=("MSE_STORE_TYPE", "MSE_OWNER_INFO", "STORE_NAME", "STORE_ID", "STORE_ADDRESS_HOUSE", "STORE_ADDRESS_ROAD",
"STORE_ADDRESS_VILLAGE", "STORE_ADDRESS_UNION", "STORE_ADDRESS_THANA", "STORE_ADDRESS_DISTRICT",
"STORE_ADDRESS_DIVISION", "STORE_EMPLOYEE_STATUS", "STORE_NUMBER_OF_EMPLOYEE",
"STORE_AVG_REVENUE", "STORE_AVG_COGS", "STORE_AVG_PROFIT", "STORE_CUSTOMER_CREDIT_LIMIT",
"STORE_BUSINESS_TARGET", "STORE_REORDER_THRESHOLD", "STORE_PASSWORD", "employees")
I was hoping that with a get request, I would get all the employees under store but I keep getting this error.
AttributeError: 'OWNER_STORE' object has no attribute 'employees'
and on the last line of terminal,
AttributeError: Got AttributeError when attempting to get a value for field employees on serializer STORE_EMPLOYEE_SERIALIZER.
The serializer field might be named incorrectly and not match any attribute or key on the OWNER_STORE instance.
Original exception text was: 'OWNER_STORE' object has no attribute 'employees'.
You need use MSE_EMPLOYEE_set instead employees.
Or add related_name to the store = models.ForeignKey(OWNER_STORE)
store = models.ForeignKey(OWNER_STORE, related_name='employees')