How to convert this method in django-rest-framework - django

I've already done this method in django. But I wanna convert this in django-rest-framework. I'm not how to do this can any one help me regarding this . I want to know how to build the serializers and views for this.
At the same time how to send additional data in this itself
sorry the code being dirty
thank you in advance...
models.py
class User(AbstractUser):
ADDCHKS_ID=models.CharField(max_length=16, blank=True, null=True)
is_active=models.BooleanField(default=False,blank=True, null=True)
is_excutive=models.BooleanField(default=False,blank=True, null=True)
class ExcutiveRegistration(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,null=True)
'''Personal Details'''
First_name = models.CharField(max_length=100,null=True ,blank=True)
Last_name = models.CharField(max_length=100,null=True ,blank=True)
DOB = models.DateField(max_length=100,null=True ,blank=True)
Fathers_name = models.CharField(max_length=100,null=True ,blank=True)
Contact_number = models.IntegerField(max_length=10,null=True ,blank=True)
Alt_Contact_number = models.IntegerField(max_length=10,null=True ,blank=True)
# Profile_picture=models.ImageField(upload_to='images/', null=True, verbose_name="")
'''Current Addresss'''
Pin_code_c = models.IntegerField(max_length=6,null=True ,blank=True)
State_c = models.CharField(max_length=50,null=True ,blank=True)
District_c = models.CharField(max_length=50,null=True ,blank=True)
Taluk_c = models.CharField(max_length=50,null=True ,blank=True)
Location_c = models.CharField(max_length=100,null=True ,blank=True)
House_no_c = models.IntegerField(max_length=4,null=True ,blank=True)
Street_c = models.CharField(max_length=100,null=True ,blank=True)
'''Permanent Address'''
Pin_code_p = models.IntegerField(max_length=6, null=True,blank=True)
State_p = models.CharField(max_length=50, null=True,blank=True)
District_p = models.CharField(max_length=50, null=True,blank=True)
Taluk_p = models.CharField(max_length=50, null=True,blank=True)
Location_p = models.CharField(max_length=100, null=True,blank=True)
House_no_p = models.IntegerField(max_length=4, null=True,blank=True)
Street_p = models.CharField(max_length=100, null=True,blank=True)
'''Reference'''
Family_reference_name = models.CharField(max_length=100, null=True,blank=True)
Family_reference_conatact_number = models.IntegerField(max_length=10, null=True,blank=True)
Neighbour_reference_name = models.CharField(max_length=100, null=True,blank=True)
Neighbour_reference_contact = models.IntegerField(max_length=10, null=True,blank=True)
'''Document Proof'''
ID_Proof_Document_Type=models.CharField(max_length=50,
choices=ID_CHOICES,
default="Voter",
null=True,
blank=True)
# ID_Proof_Document= models.ImageField(upload_to='images/', null=True, verbose_name="")
'''Bank Details'''
# Account_Name=models.CharField(max_length=50, null=True)
# Bank_name=models.CharField(max_length=50, null=True)
# Account_Number=models.CharField(max_length=50, null=True)
# IFSC_Code=models.IntegerField(max_length=15, null=True)
'''Area Covered'''
Work_State=models.CharField(max_length=50,null=True ,blank=True)
Work_covering_district=models.CharField(max_length=50,null=True ,blank=True)
Working_location=models.CharField(max_length=50,null=True ,blank=True)
Status=models.CharField(max_length=50,
choices=Status_,
default='No Action',
null=True
,blank=True)
def __str__(self):
return str(self.First_name)
class ExcutiveRegistrationPincode(models.Model):
ExcutiveRegistration=models.ForeignKey(ExcutiveRegistration, on_delete=models.CASCADE)
Covering_Pincode=models.IntegerField(max_length=6)
views.py
class ExcutiveHomeView(LoginRequiredMixin, ListView):
context_object_name = 'customers'
template_name = 'accounts/excutive/excutive_home_page.html'
def get_queryset(self, *args, **kwargs):
pincodes = [
e.Covering_Pincode
for e in ExcutiveRegistrationPincode.objects.filter(
ExcutiveRegistration__user=self.request.user
).only('Covering_Pincode')
]
return Customer.objects.filter(Pincode__in=pincodes,Status='Avaiable')

views.py
class Excutivehomepagess(generics.ListAPIView):
model=Customer
serializer_class=CustomerSerializer
def get_queryset(self):
pincodes = [
e.Covering_Pincode
for e in ExcutiveRegistrationPincode.objects.filter(
ExcutiveRegistration__user=self.request.user.id
).only('Covering_Pincode')
]
return Customer.objects.filter(Pincode__in=pincodes, Status='Avaiable')
serializers.py
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model= Customer
fields= '__all__'

Related

Return all the orderitems in an order of a customer Django

I want to return all the items in all the orders that have made a customer.
I don't know if it is possible or how I need to do it, I tried to get the orders with .get and .filter in my views but with get is only possible to return one value
My models.py
class Customer(models.Model):
user = models.OneToOneField(Account, on_delete=models.CASCADE, null=True)
first_name = models.CharField(max_length=200, null=True)
last_name = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=10, null=True, blank=True)
email = models.EmailField(null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return str(self.user)
class Category(models.Model):
name = models.CharField(max_length=200, null=True)
class Meta:
verbose_name='categoria'
verbose_name_plural ='categorias'
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField(null=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
description = models.TextField(max_length=500, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
ventas = models.IntegerField(null=True, blank=True, default=0)
image = models.ImageField(null=True, blank=True, default='Banner_Cubrebocas.png')
def __str__(self):
return self.name
class Order(models.Model):
STATUS= (
('Pending', 'Pending'),
('Delivered', 'Delivered')
)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
#product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True)
date_created =models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS, default='Pending')
complete = models.BooleanField(default=False, null=True, blank=True)
def __str__(self):
return str(self.id)
#property
def shipping(self):
shipping= False
orderitems=self.orderitem_set.all()
for i in orderitems:
if i.product.digital == False:
shipping=True
return shipping
#property
def get_cart_total(self):
orderitems= self.orderitem_set.all()
total= sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems= self.orderitem_set.all()
total= sum([item.quantity for item in orderitems])
return total
class OrderItem(models.Model):
product= models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order= models.ForeignKey(Order, on_delete=models.CASCADE, null=True)
quantity= models.IntegerField(default=0, null=True, blank=True)
date_added= models.DateTimeField(auto_now=True, null=True)
and my views.py I tried with different foms but I don't get the correct one
def customer(request, pk_test):
qs = Product.objects.all()
category_query = request.GET.get('category')
status_query = request.GET.get('status')
customer = Customer.objects.get(id=pk_test)
orders= customer.order_set.all()
orders_count = orders.count()
order = Order.objects.filter(customer__id=pk_test, complete=False)
items = order.orderitem_set.all()
#myFilter= OrderFilter(request.GET, queryset=orders)
#orders = myFilter.qs
categories = Category.objects.all()
if status_query != '' and status_query is not None:
items = items.filter(order__status__icontains=status_query)
if status_query == 'All status':
items = order.orderitem_set.all()
context = {
'customer':customer,
'orders':orders,
'orders_count':orders_count,
#'myFilter':myFilter,
'categories':categories,
'order':order,
'items':items,
}
return render(request, 'cuentas/customer.html', context)

Django inlineformset: PK missing in subform -> form_set.is_valid() = False

I have followed this tutorial to implement inlneformset.
CreateView works (data is registered in database) but UpdateView doesn't.
UpdateView is correctly displayed with correct data.
But it seems like subform (application inlineformset) is never valid and I don't understand why?
forms.py:
NAME = Thesaurus.options_list(2,'fr')
ACCESS = Thesaurus.options_list(3,'fr')
ApplicationFormset = inlineformset_factory(
Utilisateur, Application,
fields=('app_app_nom','app_dro'),
widgets={
'app_app_nom': forms.Select(choices=NAME),
'app_dro': forms.Select(choices=ACCESS)
},
extra=3,
can_delete=True,
)
models.py:
class Projet(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
pro_ide = models.AutoField(primary_key = True)
pro_nom = models.IntegerField("Nom du projet", null=True, blank=True)
pro_log = models.CharField("Log utiisateur", max_length=20, null=True, blank=True)
pro_dat = models.DateTimeField("Date log",auto_now_add=True)
pro_act = models.IntegerField("Projet en cours ?", null=True, blank=True)
log = HistoricalRecords()
class Meta:
db_table = 'tbl_pro'
verbose_name_plural = 'Projets'
ordering = ['pro_ide']
permissions = [
('can_add_project','Can add project'),
]
class Utilisateur(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
uti_ide = models.AutoField(primary_key = True)
pro_ide = models.ForeignKey(Projet, on_delete = models.CASCADE) # related project
uti_nom = models.CharField("Nom", max_length=20, null=True, blank=True)
uti_pre = models.CharField("Prénom", max_length=20, null=True, blank=True)
uti_mai = models.CharField("Email", max_length=40, null=True, blank=True)
uti_sit = models.CharField("Equipe", max_length=20, null=True, blank=True)
uti_pro = models.CharField("Fonction/profil", max_length=200, null=True, blank=True)
uti_dem_dat = models.DateTimeField("Date demande",auto_now_add=True, null=True, blank=True)
uti_val = models.IntegerField("Demande validée ?", null=True, blank=True)
uti_val_dat = models.DateTimeField("Date validation",auto_now_add=True, null=True, blank=True)
uti_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
uti_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
log = HistoricalRecords()
#classmethod
def options_list(cls,pro_ide):
projet = Projet.objects.get(pro_ide=pro_ide)
utilisateurs = Utilisateur.objects.filter(pro_ide=projet.pro_ide)
the_opts_list = [(utilisateur.uti_ide, utilisateur.uti_nom+', '+utilisateur.uti_pre) for utilisateur in utilisateurs]
the_opts_list.insert(0, (None, ''))
return the_opts_list
class Meta:
db_table = 'tbl_uti'
verbose_name_plural = 'Utilisateurs'
ordering = ['uti_ide']
class Application(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
app_ide = models.AutoField(primary_key = True)
uti_ide = models.ForeignKey(Utilisateur, on_delete = models.CASCADE) # related utilisateur
app_app_nom = models.IntegerField("Nom application", null=True, blank=True)
app_dro = models.IntegerField("Droit sur application", null=True, blank=True)
app_sta = models.IntegerField("Statut (création/Modification/Suppression", null=True, blank=True)
app_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
app_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
log = HistoricalRecords()
class Meta:
db_table = 'tbl_app'
verbose_name_plural = 'Applications'
ordering = ['app_ide']
class Administration(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
adm_ide = models.AutoField(primary_key = True)
app_ide = models.ForeignKey(Application, on_delete = models.CASCADE) # related application
adm_nom = models.CharField("Nom d'utilisateur dans l'application", max_length=20, null=True, blank=True)
adm_dem = models.IntegerField("Demande traitée ?", null=True, blank=True)
adm_dem_dat = models.DateTimeField("Date traitement de la demande",auto_now_add=True)
adm_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
adm_dat = models.DateTimeField("Date log",auto_now_add=True)
log = HistoricalRecords()
class Meta:
db_table = 'tbl_adm'
verbose_name_plural = 'Adminitrations'
ordering = ['adm_ide']
permissions = [
('can_manage_project','Can manage project'),
]
UpdateView:
class UtilisateurUpdateView(UpdateView):
model = Utilisateur
fields = ['uti_nom','uti_pre','uti_mai','uti_sit','uti_pro']
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data["utilisateur"] = self.request.user.username
data["application"] = ApplicationFormset(self.request.POST, instance=self.object)
else:
data["application"] = ApplicationFormset(instance=self.object)
return data
def form_valid(self, form):
context = self.get_context_data()
application = context["application"]
self.object = form.save()
self.object.save()
if application.is_valid(): # ***** NEVER VALID *****
application.instance = self.object
print('application.instance',application.instance)
application.app_app_nom = application.instance.cleaned_data['app_app_nom']
application.app_dro = application.instance.cleaned_data['app_dro']
application.app_log = context["utilisateur"]
application.uti_ide = 1
application.save()
return super().form_valid(form)
def get_success_url(self):
return reverse("project:index")
I have resolve my problem: I forget to insert form_set id in my html template (app_ide in my case)

'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'

'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'.
i am getting error on 'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'. any help, would be appreciated.
'DemoAppProductUpdateDestroySerializer' object has no attribute
'get_image'
models.py
class Product(models.Model):
title = models.CharField(max_length=30)
slug= models.SlugField(blank=True, null=True)
sku = models.CharField(max_length=30)
description = models.TextField(max_length=200, null=True, blank=True)
instruction = models.TextField(max_length=200, null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits= 10,)
discount_price= models.DecimalField(decimal_places=2, max_digits= 10, null=True, blank=True)
brand = models.ForeignKey("Brand", null=True, blank=True, on_delete=models.CASCADE)
waist = models.ForeignKey("Waist", null=True, blank=True, on_delete=models.CASCADE)
occasion = models.ForeignKey("Occasion", null=True, blank=True, on_delete=models.CASCADE)
style = models.ForeignKey("Style", null=True, blank=True, on_delete=models.CASCADE)
neck = models.ForeignKey("Neck", null=True, blank=True, on_delete=models.CASCADE)
fit = models.ForeignKey("Fit", null=True, blank=True, on_delete=models.CASCADE)
pattern_type = models.ForeignKey("Pattern_Type", null=True, blank=True, on_delete=models.CASCADE)
color = models.ForeignKey("Color", null=True, blank=True, on_delete=models.CASCADE)
size = models.ManyToManyField("Size", null=True, blank=True)
sleeve = models.ForeignKey("Sleeve_Length", null=True, blank=True, on_delete=models.CASCADE)
material = models.ForeignKey("Material", null=True, blank=True, on_delete=models.CASCADE)
category = models.ManyToManyField('Category', )
default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True, on_delete=models.CASCADE)
created_on = models.DateTimeField(default=timezone.now)
updated_on = models.DateTimeField(null=True, blank=True)
status = models.BooleanField(default=True)
class Meta:
ordering = ["-id"]
def __str__(self): #def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("product_detail", kwargs={"pk": self.pk})
def get_image_url(self):
img = self.productimage_set.first()
if img:
return img.image.url
return img #None
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(pre_save_post_receiver, sender=Product)
def image_upload_to(instance, filename):
title = instance.product.title
slug = slugify(title)
basename, file_extension = filename.split(".")
new_filename = "%s-%s.%s" %(slug, instance.id, file_extension)
return "products/%s/%s" %(slug, new_filename)
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
image = models.ImageField(upload_to=image_upload_to)
created_on = models.DateTimeField(default=timezone.now)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.product.title
views.py
class ProductUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
model = Product
queryset = Product.objects.all()
serializer_class = DemoAppProductUpdateDestroySerializer
permission_classes = [IsAdminUser]
authentication_classes = [BasicAuthentication]
serializers.py
class DemoAppProductUpdateDestroySerializer(serializers.ModelSerializer):
image = serializers.SerializerMethodField()
class Meta:
model = Product
fields=[
"id",
"title",
"slug",
"sku",
"price",
"discount_price",
"image",
]
def get_image(self, obj):
return obj.productimage_set.first().image.url

Django Custom Tables Creation

I have a project where i have to create a command table for the customers to command on the site. What I am trying to achieve is to give the possibility of selecting multiple products to the customer. The foreign key is ok for one product, but when we have to select multiple ones, is not ok. Even when clicking the "+"add button, you are not allowed to add more, but django makes you add a new product in the DB :D.
How can i achieve my target of adding multiple products to the cart?
Thank you in advance!
My models;
from django.db import models
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from datetime import datetime, timedelta, time
today = datetime.now().date()
class ClientManager(models.Manager):
def active(self, *args, **kwargs):
return super(ClientManager, self).filter(timestamp__lte=datetime.now())
class Client(models.Model):
TYPE_CLIENT = (
('PF', 'Persoana Fizica'), ('PJ', 'Persoana Juridica'),)
MODEL_CLIENT = (
('O', 'On-line'), ('S', 'Showroom'), ('D', 'Distribuitor'))
user = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True, null=True, default=1, on_delete=True)
model_client = models.CharField(max_length=3, blank=True, default="PF", null=True,
choices=MODEL_CLIENT, help_text='Selecteaza de unde vine clientul')
tip_client = models.CharField(max_length=3, blank=True, default="PF", null=True,
choices=TYPE_CLIENT, help_text='Selecteaza tipul de client')
nume_client = models.CharField(max_length=30, blank=True, default="", null=True,
help_text='Insereaza Numele si Prenumele Clientului')
adresa_client = models.CharField(max_length=50, blank=True, default="", null=True,help_text='Insereaza Adresa Clientului')
cnp_client = models.CharField(
max_length=12, blank=True, default="", null=True, help_text='Insereaza CNP-ul Clientului')
serie_numar_client = models.CharField(max_length=20, blank=True, default="", null=True,help_text='Insereaza Seria si Numarul Clientului')
email = models.EmailField(blank=True, null=True)
nume_firma = models.CharField(max_length=30, blank=True, default="",null=True, help_text='Insereaza Numele Firmei')
cui_firma=models.CharField(max_length=10, blank=True, default="",null=True, help_text='Insereaza CUI-ul Firmei')
adresa_firma = models.CharField(
max_length=70, blank=True, default="", null=True, help_text='Insereaza Adresa Firmei')
updated = models.DateTimeField(auto_now=True, auto_now_add=False, blank=True, null=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, blank=True, null=True)
objects = ClientManager()
def __str__(self):
return str(self.nume_client) + " | " + str(self.adresa_client) + " | " + str(self.adresa_firma) + " | " + str(self.nume_firma) + " | " + str(self.timestamp)
class Meta:
verbose_name_plural = "client"
ordering = ["-timestamp"]
class ProdusManager(models.Manager):
def active(self, *args, **kwargs):
return super(ProdusManager, self).filter(timestamp__lte=datetime.now())
class Produs(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
blank=True, null=True, default=1, on_delete=True)
nume_produs = models.CharField(max_length=30, blank=True, null=True,
help_text='Adauga Nume Produs')
pret_produs = models.IntegerField(blank=True, null=True,help_text='Introdu Pretul Produsului')
timestamp = models.DateTimeField(
auto_now=False, auto_now_add=True, blank=True, null=True)
objects = ProdusManager()
def __str__(self):
return str(self.nume_produs) + " | " + str(self.pret_produs)
class Meta:
verbose_name_plural = "produs"
ordering = ["-timestamp"]
class ComandaManager(models.Manager):
def active(self, *args, **kwargs):
return super(ComandaManager, self).filter(timestamp__lte=datetime.now())
class Comanda(models.Model):
STATUS_PRODUS = (
('S', 'Stoc'), ('SD', 'Stoc Distribuitor'), ('L', 'Livrat'))
user = models.ForeignKey(settings.AUTH_USER_MODEL,
blank=True, null=True, default=1, on_delete=True)
nume_client_comanda = models.ForeignKey(
Client, related_name='nume_client_comanda', on_delete=models.CASCADE)
nume_firma_comanda = models.ForeignKey(
Client, related_name='nume_firma_comanda', on_delete=models.CASCADE)
produsul_comandat = models.ForeignKey(
Produs, related_name='produsul_comandat', on_delete=models.CASCADE)
pretul_comandat = models.ForeignKey(
Produs, related_name='pretul_comandat', on_delete=models.CASCADE)
cantitate = models.IntegerField (blank = True, null = True, help_text = 'Introdu Cantitatea Produsului')
status_produs = models.CharField(max_length=3, blank=True, default="PF", null=True,
choices=STATUS_PRODUS, help_text='Selecteaza de unde vine clientul')
pret_comanda = models.IntegerField(
blank=True, null=True, help_text='Introdu Pretul Comenzii')
timestamp = models.DateTimeField(
auto_now=False, auto_now_add=True, blank=True, null=True)
objects = ComandaManager()
def __str__(self):
return str(self.nume_client_comanda) + " | " + str(self.pret_comanda)
# def __str__(self):
# return "%s %s" % (self.first_name, self.last_name)
class Meta:
verbose_name_plural = "comanda"
ordering = ["-timestamp"]
You need a Many to Many relationship, not ForeignKey (Many-to-One)
This way multiple Clients can each have multiple Products.
Right now, two different Clients cannot have the same Product because you used ForeignKey.

How can I allow a user to filter models dynamically and export only certain fields?

I've been asked to design a way for people to search through multiple models on criteria they enter and allow them to export any number of fields they select.
Example:
User enters "Teacher" as a term for Job Title and "Google" for a Work Site Location but want to export "Employee ID", "First Name", "Last Name", "Date of Birth"
I'm sure this is possible, but I'm at a complete loss for where to start.
My models (for reference) are here:
import datetime
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.utils import timezone
class Classification(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Classification Name')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Classification'
verbose_name = 'Classification'
verbose_name_plural = 'Classifications'
class Location(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name')
aeries_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='Aeries ID')
county_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='County ID')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Location'
verbose_name = 'Location'
verbose_name_plural = 'Locations'
ordering = ['name']
class Person(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True)
current_identity = models.ForeignKey('PersonIdentity', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Current Identity', related_name='current_identity')
employee_id = models.CharField(max_length=255, null=False, blank=False, verbose_name='Employee ID')
birthdate = models.DateField(blank=True, null=True, verbose_name='Birthdate')
original_hire_date = models.DateField(blank=True, null=True, verbose_name='Original Hire Date')
def __str__(self):
if self.current_identity is not None:
return '{}'.format(str(self.current_identity))
else:
return "{}".format(self.employee_id)
#property
def current_age(self):
from dateutil.relativedelta import relativedelta
difference_in_years = relativedelta(timezone.now().date(), self.birthdate).years
return difference_in_years
def primary_assignment(self):
return self.jobassignment_set.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).order_by('priority')[0]
#property
def display_name(self):
if self.current_identity:
return '{0.first_name} {0.last_name} ({1.employee_id})'.format(self.current_identity, self)
else:
return 'Employee ID {0.employee_id}'.format(self)
#property
def is_certificated(self):
assignments = JobAssignment.objects.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).filter(
person=self,
classification__name__icontains="Certificated"
)
return assignments.count() >= 1
class Meta:
db_table = 'Person'
verbose_name = 'Person'
verbose_name_plural = 'People'
class PersonIdentity(models.Model):
person = models.ForeignKey(Person, verbose_name='Person', on_delete=models.CASCADE)
first_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='First Name')
middle_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='Middle Name')
last_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='Last Name')
start_date = models.DateField(blank=False, null=False, default=datetime.date.today, verbose_name='Start Date')
end_date = models.DateField(blank=True, null=True, verbose_name='End Date')
def __str__(self):
first_name = '' if self.first_name is None else self.first_name
last_name = '' if self.last_name is None else self.last_name
if self.middle_name is not None and self.middle_name != '':
return "{} {}. {} ({})".format(first_name, self.middle_name[0], last_name, self.person.employee_id)
else:
return "{} {} ({})".format(first_name, last_name, self.person.employee_id)
def save(self, *args, **kwargs):
change_identity = False
if not self.id:
change_identity = True
super().save(*args, **kwargs)
if change_identity:
self.person.current_identity = self
self.person.save()
class Meta:
db_table = 'PersonIdentity'
verbose_name = 'Person Identity'
verbose_name_plural = 'Person Identities'
ordering = ['end_date', 'last_name', 'first_name']
class Contact(models.Model):
person = models.OneToOneField(Person, on_delete=models.CASCADE, verbose_name='Person')
email_address = models.EmailField(blank=True, null=True, verbose_name='Primary Email')
phone_number = models.CharField(max_length=15, blank=True, null=True, verbose_name='Phone Number')
phone_extension = models.CharField(max_length=255, blank=True, null=True, verbose_name='Phone Extension')
address1 = models.CharField(max_length=255, blank=True, null=True, verbose_name='Address 1')
address2 = models.CharField(max_length=255, blank=True, null=True, verbose_name='Address 2')
city = models.CharField(max_length=255, blank=True, null=True, verbose_name='City')
state = models.CharField(max_length=2, default='CA', blank=True, null=True, verbose_name='State')
postal = models.CharField(max_length=5, blank=True, null=True, verbose_name='Postal Code')
def __str__(self):
return '{}'.format(self.person.current_identity)
class Meta:
db_table = 'Contact'
verbose_name = 'Contact'
verbose_name_plural = 'Contacts'
class Department(models.Model):
department_id = models.CharField(max_length=5, blank=False, null=False, verbose_name='Department ID')
description = models.CharField(max_length=255, blank=False, null=False, verbose_name='Department Description')
def __str__(self):
return '{}'.format(self.description)
class Meta:
db_table = 'Department'
verbose_name = 'Department'
verbose_name_plural = 'Departments'
class Job(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name')
code = models.CharField(max_length=255, blank=False, null=False, verbose_name='Code')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Job'
verbose_name = 'Job'
verbose_name_plural = 'Jobs'
class JobPosition(models.Model):
job = models.ForeignKey(Job, blank=True, null=True, verbose_name='Job')
reports_to = models.ForeignKey('JobPosition', blank=True, null=True, verbose_name='Reports To')
name = models.CharField(max_length=255, blank=True, null=True, verbose_name='Name')
number = models.CharField(max_length=255, blank=False, null=False, verbose_name='Number')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'JobPosition'
verbose_name = 'Job Position'
verbose_name_plural = 'Job Positions'
class JobAssignment(models.Model):
person = models.ForeignKey(Person, blank=False, null=False, verbose_name='Person')
position = models.ForeignKey(JobPosition, blank=False, null=False, verbose_name='Position')
location = models.ForeignKey(Location, blank=True, null=True, verbose_name='School')
classification = models.ForeignKey(Classification, blank=True, null=True, verbose_name='Classification')
start_date = models.DateField(blank=True, null=True, verbose_name='Start Date')
end_date = models.DateField(blank=True, null=True, verbose_name='End Date')
effective_date = models.DateField(blank=True, null=True, verbose_name='Effective Date')
fte = models.CharField(max_length=10, blank=True, null=True, verbose_name='FTE')
seniority_date = models.DateField(blank=True, null=True, verbose_name='Seniority Date')
last_start_date = models.DateField(blank=True, null=True, verbose_name='Last Start Date')
last_pay_date = models.DateField(blank=True, null=True, verbose_name='Last Pay Date')
entry_date = models.DateField(blank=True, null=True, verbose_name='Position Entry Date')
record_number = models.IntegerField(default=0, verbose_name='Position Record Number')
pay_group = models.CharField(max_length=3, blank=True, null=True, verbose_name='Pay Group')
indicator = models.CharField(max_length=1, blank=True, null=True, verbose_name='Indicator')
full_or_part_time = models.CharField(max_length=1, blank=True, null=True, verbose_name='Full/Part')
standard_hours_per_week = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, verbose_name='Standard Hours per Week')
pay_status = models.CharField(max_length=1, blank=True, null=True, verbose_name='Pay Status')
comp_rate = models.DecimalField(max_digits=15, decimal_places=6, blank=True, null=True, verbose_name='Comp Rate')
comp_frequency = models.CharField(max_length=10, blank=True, null=True, verbose_name='Comp Freq')
hourly_rate = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name='Hrly Rate')
daily_rate = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name='Daily Rt')
rate_code = models.CharField(max_length=10, blank=True, null=True, verbose_name='Rate Code')
compensation_rate = models.DecimalField(max_digits=15, decimal_places=6, blank=True, null=True, verbose_name='Compensation Rate')
total_cdays = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, verbose_name='TOTAL_CDAYS')
teacher_hours = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True, verbose_name='Teacher Hours')
def __str__(self):
return '{} - {}'.format(self.position.name, self.position.number)
#classmethod
def current_assignments(cls):
return cls.objects.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).exclude(person__ssn__isnull=True).exclude(person__current_identity__isnull=True).exclude(person__contact__isnull=True)
class Meta:
db_table = 'JobAssignment'
verbose_name = 'Job Assignment'
verbose_name_plural = 'Job Assignments'
ordering = ['location__name', 'person__current_identity__last_name', 'person__current_identity__first_name', 'position__name']