I have two apps in Django project . one is "accounts" another is " Courses "
I have a model in accounts app
class Student(SoftDeleteModel):
user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='student_info')
name = models.CharField(null=True, blank=True, max_length=250)
course_enrolled = models.ForeignKey(Courses,on_delete=models.CASCADE,blank=True)
trx_id = models.CharField(max_length=20)
date_of_birth = models.DateField(null=True, blank=True)
education_qualification = models.CharField(null=True, blank=True, max_length=250)
institution_name = models.CharField(null=True, blank=True, max_length=250)
image = models.ImageField(upload_to='photos/%y/%m/%d',null=True, blank=True)
address = models.CharField(null=True, blank=True, max_length=250)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.email
class Instractor(SoftDeleteModel):
user = models.OneToOneField(to=User, on_delete=models.CASCADE, related_name='instractor_info')
name = models.CharField(null=True, blank=True, max_length=250)
degination = models.CharField(null=True, blank=True, max_length=250)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
This is model for accounts
and Course Model is:
from accounts.models import *
class Courses(models.Model):
title = models.CharField(max_length=200,blank=True,null=True)
image = models.ImageField(null=True,upload_to="photos/course/")
category = models.ForeignKey(Category,on_delete=models.CASCADE)
instractor = models.ForeignKey(Instractor, on_delete=models.CASCADE,blank=True)
total_student_enrolled = models.IntegerField(null=True,blank=True)
price = models.IntegerField(blank=True,null=True)
course_length_in_hour = models.IntegerField(blank=True,null=True)
course_length_in_weeks = models.IntegerField(blank=True,null=True)
programming_language = models.CharField(max_length=500,null=True,blank=True)
course_requirements = models.TextField()
course_description = models.TextField()
what_you_will_learn = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateField(auto_now_add=True)
is_published = models.BooleanField(default=False)
slug = models.SlugField(null = False, blank = True)
def __str__(self):
return self.title
I have import courses.model but it showing that Instractor not Defined. But if i remove
course_enrolled = models.ForeignKey(Courses,on_delete=models.CASCADE,blank=True)
course_enrolled field from accounts model the error is not showing :/
I don't get what is the problem is .
Error Message is :
instractor = models.ForeignKey(Instractor, on_delete=models.CASCADE,blank=True)
NameError: name 'Instractor' is not define
You need to put the model name in quotes when defining a FK:
instractor = models.ForeignKey("accounts.Instractor", on_delete=models.CASCADE,blank=True)
Related
I was trying to delete my Apllication model:
class Application(models.Model):
app_type = models.ForeignKey(ApplicationCategory, on_delete=models.CASCADE, related_name='applications')
fio = models.CharField(max_length=40)
phone_number = models.CharField(max_length=90)
organisation_name = models.CharField(max_length=100, null=True, blank=True)
aid_amount = models.PositiveIntegerField()
pay_type = models.CharField(max_length=1, choices=PAY_CHOICES, default=PAY_CHOICES[0][0])
status = models.ForeignKey(AppStatus, on_delete=models.CASCADE, related_name='applications', null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
benefactor = models.ForeignKey(Benefactor, on_delete=models.CASCADE, related_name='applications', null=True)
def __str__(self):
return f"id={self.id} li {self.fio} ning mablag\'i!"
and this was my Benefactor model:
class Benefactor(models.Model):
fio = models.CharField(max_length=255)
phone_number = models.CharField(max_length=9)
image = models.ImageField(upload_to='media/')
sponsory_money = models.IntegerField()
organisation_name = models.CharField(max_length=55, null=True, blank=True)
def __str__(self):
return f"{self.fio}"
But I got the below message on superAdmin Panel:
TypeError at /admin/api/benefactor/
create_reverse_many_to_one_manager.\<locals\>.RelatedManager.__call__() missing 1 required keyword-only argument: 'manager'
I would expect delete smoothly!!
Your Benefactor model has several ForeignKey relationships that share the related_name. Give each a unique name and rerun your migrations.
I have a product model. I need to autocomplete product name into input field. How can I code?
class Product(models.Model):
product_name = models.CharField(max_length=255)
product_detail = models.TextField(blank=True, null=True)
product_price = models.FloatField(blank=True)
category = models.CharField(max_length=30)
product_image = models.ImageField(upload_to='pictures/%Y/%m/%d/', max_length=255, blank=True, null=True)
product_amount = models.IntegerField(blank=True, null=True)
del_flag = models.BooleanField(default=False)
def __str__(self):
return self.product_name
I need to create double reverse queryset in Django, explained more in the code:
The models
class Book(models.Model):
date = models.DateTimeField(auto_now=True)
book_name = models.CharField(max_length=150)
book_level = models.ForeignKey(Level, on_delete=CASCADE)
book_subject = models.ForeignKey(Subject, on_delete=CASCADE)
book_teacher = models.ForeignKey(Teacher, on_delete=CASCADE, null=True, blank=True)
book_comission = models.DecimalField(max_digits=19, decimal_places=5, null=True, blank=True)
book_black_papers = models.IntegerField()
book_color_papers = models.IntegerField()
book_paper_cost = models.DecimalField(max_digits=19, decimal_places=5)
book_ink_cost = models.DecimalField(max_digits=19, decimal_places=5)
book_color_ink_cost = models.DecimalField(max_digits=19, decimal_places=5)
book_cover_cost = models.DecimalField(max_digits=19, decimal_places=5)
supplier = models.ForeignKey(Supplier, on_delete=CASCADE, null=True, blank=True)
book_total_cost = models.DecimalField(max_digits=19, decimal_places=5)
book_sell_price = models.DecimalField(max_digits=19, decimal_places=5)
viewed_by = models.ManyToManyField(User)
is_double_pages = models.BooleanField(default=False)
is_hidden = models.BooleanField(default=False)
image1 = ProcessedImageField(upload_to='book_image',
processors=[ResizeToFill(440, 262)],
format='JPEG',
options={'quality': 60}, blank=True, null=True)
image2 = ProcessedImageField(upload_to='book_image',
processors=[ResizeToFill(440, 262)],
format='JPEG',
options={'quality': 60}, blank=True, null=True)
image3 = ProcessedImageField(upload_to='book_image',
processors=[ResizeToFill(440, 262)],
format='JPEG',
options={'quality': 60}, blank=True, null=True)
image4 = ProcessedImageField(upload_to='book_image',
processors=[ResizeToFill(440, 262)],
format='JPEG',
options={'quality': 60}, blank=True, null=True)
published_online = models.BooleanField(default=False)
class VIPSellInvoice(models.Model):
ordered = 'تحت التنفيذ'
delivered = 'منتهية'
canceled = 'ملغاة'
invoice_choices = (
(ordered, 'تحت التنفيذ'),
(delivered, 'منتهية'),
(canceled, 'ملغاة'),
)
date = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=PROTECT)
client = models.ForeignKey(VipClient, on_delete=PROTECT)
total = models.DecimalField(max_digits=19, decimal_places=5, default=0)
status = models.CharField(max_length=160, choices=invoice_choices)
delivery = models.ForeignKey(Delivery, on_delete=PROTECT, null=True, blank=True)
delivery_price = models.DecimalField(max_digits=19, decimal_places=5, default=0, null=True, blank=True)
delivery_notes = models.CharField(max_length=500, null=True, blank=True)
is_done = models.BooleanField(default=False)
class VipPriceList(models.Model):
book_name = models.ForeignKey(Book, on_delete=CASCADE)
book_price = models.DecimalField(max_digits=19, decimal_places=5)
book_client = models.ForeignKey(VipClient, on_delete=CASCADE)
book_client_comission = models.DecimalField(max_digits=19, decimal_places=5)
class VipClient(models.Model):
client_name = models.CharField(max_length=150)
client_address = models.CharField(max_length=150)
client_phone1 = models.CharField(max_length=20)
client_phone2 = models.CharField(max_length=20)
client_note = models.CharField(max_length=500, null=True, blank=True)
client_balance = models.DecimalField(max_digits=19, decimal_places=5, default=0)
client_commission = models.DecimalField(max_digits=19, decimal_places=5, default=0)
Am trying to get the VIPpricelists`` that belong to theclientthat belongs to the currentVip Invoicethen get theBook_set` in the final queryset so that I can deal with it.
here is howw i tried to call it in my views:
def vip_sellinvoice_add_books(request, pk):
current_vip_invoice = get_object_or_404(models.VIPSellInvoice, pk=pk)
test = current_vip_invoice.client.vippricelist_set.all().book_set.all()
context = {
'test': test,
}
return render(request, 'vip/vip_sell_invoice_add_books.html', context)
I get the error:
'QuerySet' object has no attribute 'book_set'
so, is it possible to create such a nested reverse querysets in Django or there is a simpler way to do it?
In that case, you usually query from the Book object itself, like:
Book.objects.filter(vippricelist__book_client__vIPsellinvoice=current_vip_invoice)
So here we query for Books for which there exists a VipPriceList object which has a book_client field that refers to a VipClient that is related to the current_vip_invoice).
I've been strugglin to relate a csv imported data model with a spatial data model based on a CharField.
I've created both models and now im trying to transfer the data from one field to a new one to be the ForeignKey field. I made a Runpython funtion to apply on the migration but it goives the an error:
ValueError: Cannot assign "'921-5'":
"D2015ccccccc.rol_fk" must be a "D_Base_Roles" instance.
Here are the models:
class D_Base_Roles(models.Model):
predio = models.CharField(max_length=254)
dest = models.CharField(max_length=254)
dir = models.CharField(max_length=254)
rol = models.CharField(primary_key=True, max_length=254)
vlr_tot = models.FloatField()
ub_x2 = models.FloatField()
ub_y2 = models.FloatField()
instrum = models.CharField(max_length=254)
codzona = models.CharField(max_length=254)
nomzona = models.CharField(max_length=254)
geom = models.MultiPointField(srid=32719)
def __str__(self):
return str(self.rol)
class Meta():
verbose_name_plural = "Roles"
class D2015ccccccc(models.Model):
id = models.CharField(primary_key=True, max_length=80)
nombre_archivo = models.CharField(max_length=180, blank=True, null=True)
derechos = models.CharField(max_length=120, blank=True, null=True)
dir_calle = models.CharField(max_length=120, blank=True, null=True)
dir_numero = models.CharField(max_length=120, blank=True, null=True)
fecha_certificado = models.CharField(max_length=50, blank=True, null=True)
numero_certificado = models.CharField(max_length=50, blank=True, null=True)
numero_solicitud = models.CharField(max_length=50, blank=True, null=True)
rol_sii = models.CharField(max_length=50, blank=True, null=True)
zona_prc = models.CharField(max_length=120, blank=True, null=True)
##NEW EMPTY FOREIGNKEY FIELD
rol_fk = models.ForeignKey(D_Base_Roles, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return str(self.numero_certificado)
class Meta:
managed = True
#db_table = 'domperm2015cip'
verbose_name_plural = "2015 Certificados Informaciones Previas"
ordering = ['numero_certificado']
The Runpython function:
def pop_rol(apps, schema_editor):
roles = apps.get_model('b_dom_edificacion', 'D2015ccccccc')
for r in roles.objects.all():
rol = roles
r.rol_fk = r.rol_sii
r.save()
D_Base_Roles.rol values are all unique, and 921-5 is one of those values.
What am I missing?
You probably need to assign an object, not a string. Change the line
r.rol_fk = r.rol_sii
to
r.rol_fk = D_Base_Roles.objects.get(rol=r.rol_sii)
Maybe adjust to whatever the correct field for looking up D_Base_Roles instances is.
Note: this will make a database query for every iteration of the for-loop
I am new to django and i am facing a problem in displaying the average of time
My database model is
from django.db import models
class Employee(models.Model):
class Meta:
db_table = 'Employee'
emp_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100, blank=True, null=True)
department_id = models.IntegerField(blank=True, null=True)
position = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.name
class AttendanceRecord(models.Model):
class Meta:
db_table = 'AttendanceRecord'
emp_id = models.ForeignKey(Employee, on_delete=models.CASCADE)
# emp_id = models.CharField(max_length=100, blank=True, null=True)
date = models.CharField(max_length=100, blank=True, null=True)
miti = models.CharField(max_length=100, blank=True, null=True)
day = models.CharField(max_length=100, blank=True, null=True)
in_time = models.CharField(max_length=100, blank=True, null=True)
out_time = models.CharField(max_length=100, blank=True, null=True)
punch_count = models.IntegerField(blank=True, null=True)
time_spent = models.FloatField(blank=True, null=True)
difference_time = models.FloatField(blank=True, null=True)
def __str__(self):
return self.emp_id.name
class Department:
class Meta:
db_table = 'Department'
department_id = models.IntegerField(primary_key=True)
staff_count= models.IntegerField()
My Report view is:
I want to average the in_time so that i can average it and display in the report template. i cant figure out how.
from attendance.models import AttendanceRecord
class Report:
def get_all_employee_data(from_date, to_date):
all_employee_list = AttendanceRecord.objects.filter(miti__gt=from_date, miti__lt=to_date).order_by(
'-miti')
return all_employee_list
def get_specific_emp_data(from_date, to_date, e_id):
specific_employee_list = AttendanceRecord.objects.filter(miti__gt=from_date, miti__lt=to_date,
emp_id=e_id).order_by('-miti')
return specific_employee_list
My test data looks like this
TEST DATA