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.
Related
I am newbie and I am making a map visualization in Django. I will use both heatmap and marker on my website. If I add 'user_report__date' in the df there is an error ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''.
How can I add date in df so that I can use heatmaptime of folium. Thanks
Views
def index(request):
df = pd.DataFrame(IncidentGeneral.objects.values('user_report__latitude', 'user_report__longitude', 'accident_factor'))
# coordenadas = list(IncidentGeneral.objects.values_list('user_report__latitude','user_report__longitude'))[-1]
map1 = folium.Map(location=[14.676208, 121.043861],
zoom_start=12)
# df = df.dropna(axis=0, subset=['user_report__latitude', 'user_report__longitude', 'accident_factor', 'user_report__date'])
# mapquestopen
fg=folium.FeatureGroup(name='Marker Cluster', show=False)
map1.add_child(fg)
fg2=folium.FeatureGroup(name='Heat Map', show=True)
map1.add_child(fg2)
fg3=folium.FeatureGroup(name='Map with Markers', show=False)
map1.add_child(fg3)
plugins.HeatMap(df).add_to(fg2)
FastMarkerCluster(data=df.values.tolist()).add_to(fg)
# marker_cluster = MarkerCluster().add_to(fg)
folium.TileLayer(('openstreetmap'), attr='openstreetmap').add_to(map1)
# folium.TileLayer('mapquestopen', attr='mapquestopen').add_to(map1)
# folium.TileLayer('MapQuest Open Aerial', attr='MapQuest Open Aerial').add_to(map1)
folium.TileLayer('cartodbpositron', attr='cartodbpositron').add_to(map1)
folium.TileLayer('cartodbdark_matter', attr='cartodbdark_matter').add_to(map1)
plugins.Fullscreen(position='topright').add_to(map1)
folium.LayerControl().add_to(map1)
for id,row in df.iterrows():
folium.Marker(location=[row['user_report__latitude'],row['user_report__longitude']], popup=row['accident_factor']).add_to(fg3)
# folium.Marker(coordenadas).add_to(map1)
# df['user_report__date'] = df['user_report__date'].sort_values(ascending=True)
# data = []
# for _, d in df.groupby('user_report__date'):
# data.append([[row['user_report__latitude'], row['user_report__longitude'], row['accident_factor']] for _, row in d.iterrows()])
map1 = map1._repr_html_()
context = {
'map1': map1
}
return render(request, 'index.html', context)
Models
class IncidentGeneral(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True)
user_report = models.OneToOneField(UserReport, on_delete=models.CASCADE)
accident_factor = models.ForeignKey(AccidentCausation, on_delete=models.SET_NULL, blank=True, null=True)
accident_subcategory = models.ForeignKey(AccidentCausationSub, on_delete=models.SET_NULL, blank=True, null=True)
collision_type = models.ForeignKey(CollisionType, on_delete=models.SET_NULL, blank=True, null=True)
collision_subcategory = models.ForeignKey(CollisionTypeSub, on_delete=models.SET_NULL, blank=True, null=True)
crash_type = models.ForeignKey(CrashType, on_delete=models.SET_NULL, blank=True, null=True)
weather = models.PositiveSmallIntegerField(choices=WEATHER, blank=True, null=True)
light = models.PositiveSmallIntegerField(choices=LIGHT, blank=True, null=True)
severity = models.PositiveSmallIntegerField(choices=SEVERITY, blank=True, null=True)
movement_code = models.CharField(max_length=250, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class UserReport(models.Model):
PENDING = 1
APPROVED = 2
REJECTED = 3
STATUS = (
(PENDING, 'Pending'),
(APPROVED, 'Approved'),
(REJECTED, 'Rejected')
)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
description = models.TextField(max_length=250, blank=True)
address = models.CharField(max_length=250)
country = models.CharField(max_length=50, blank=True, null=True)
state = models.CharField(max_length=50, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
pin_code = models.CharField(max_length=6, blank=True, null=True)
latitude = models.FloatField(max_length=20, blank=True, null=True)
longitude = models.FloatField(max_length=20, blank=True, null=True)
upload_photovideo = models.FileField(upload_to='incident_report/image', blank=True, null=True)
date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True)
time = models.TimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
status = models.PositiveSmallIntegerField(choices=STATUS, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def get_status(self):
if self.status == 1:
incident_status = 'Pending'
elif self.status == 2:
incident_status = 'Approved'
elif self.status == 3:
incident_status = 'Rejected'
return incident_status
def save(self, *args, **kwargs):
super(UserReport, self).save(*args, **kwargs)
if self.upload_photovideo:
if ".jpg" in self.upload_photovideo.url or ".png" in self.upload_photovideo.url:
#check if image exists before resize
img = Image.open(self.upload_photovideo.path)
if img.height > 1080 or img.width > 1920:
new_height = 720
new_width = int(new_height / img.height * img.width)
img = img.resize((new_width, new_height))
img.save(self.upload_photovideo.path)
I have phone numbers stored as (921) 414-1313 in the database and I want to run a search lookup on that field, but I don't want to force them to include (, ' ', ) or -.
I'm using Postgres and tried to work with SearchVector initially, however it ran into the same challenge (so for now, I'm doing it the old fashioned way).
I have a model definition that returns an "unformatted" number as 9214141313, but I can't figure out how to query against my custom definition inside of the model?
Ultimately, I want a customer to be able to type in 921414 and get the response for the matching record.
GitHub:
https://github.com/varlenthegray/wcadmin/blob/dev/main/views.py#L25
Model:
class JobSite(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
quickbooks_id = models.IntegerField(editable=False, null=True, blank=True)
name = models.CharField(max_length=200, null=True, blank=True)
first_name = models.CharField(max_length=200, null=True, blank=True)
last_name = models.CharField(max_length=200, null=True, blank=True)
print_on_check_name = models.CharField(max_length=200, null=True, blank=True)
address = models.CharField(max_length=200, null=True, blank=True)
address_2 = models.CharField(max_length=200, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
state = models.CharField(max_length=50, null=True, blank=True)
zip = models.CharField(max_length=20, null=True, blank=True)
phone_number = models.CharField(max_length=30, null=True, blank=True)
email = models.CharField(max_length=400, null=True, blank=True)
service_interval = models.IntegerField(default=12)
next_service_date = models.DateField(null=True, blank=True)
primary_technician = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
active = models.BooleanField(default=True)
access_code = models.CharField(max_length=10, null=True, blank=True)
bill_parent = models.BooleanField(default=False)
requires_supporting_technician = models.BooleanField(default=False)
service_scheduled = models.BooleanField(default=False)
disable_service = models.BooleanField(default=False)
qb_created_on = models.DateTimeField(null=True, blank=True)
def __str__(self):
return f'{self.name}'
def phone_digits_only(self):
return re.sub("[^0-9]", "", self.phone_number)
#property
def is_past_due(self):
ignore_after = timezone.localdate() - relativedelta(years=5)
# noinspection StrFormat
if self.next_service_date:
if ignore_after >= self.next_service_date:
return False
else:
return timezone.localdate() > self.next_service_date
else:
return False
#property
def is_due_soon(self):
ignore_after = timezone.localdate() - relativedelta(years=3)
if self.next_service_date and self.next_service_date >= ignore_after:
three_months_future = timezone.localdate() + relativedelta(months=2)
return three_months_future > self.next_service_date
else:
return False
Views.py
def search_system(request, search_term=False):
if search_term:
job_sites = JobSite.objects.filter(
Q(first_name__icontains=search_term) |
Q(last_name__icontains=search_term) |
Q(quickbooks_id__icontains=search_term) |
Q(email__icontains=search_term) |
Q(phone_number_digits=search_term)
)
else:
job_sites = JobSite.objects.all().prefetch_related('customer')
data = []
for job in job_sites:
if job.first_name and job.last_name:
name = job.first_name + ' ' + job.last_name
elif job.customer.company:
name = job.customer.company
else:
name = job.customer.first_name + ' ' + job.customer.last_name
this_job = {'value': name}
data.append(this_job)
return JsonResponse(data, safe=False)
The best solution IMHO is to use the library phonenumbers which is very cleaned and well maintained.
Then do a custom "phone_cleaned" field where you add the signals "create" and "update" for this model, and update phone_cleaned accordingly (using the library to clean the phone number). And use that phone_cleaned to do all your searches.
I want to make pay form, but I cannot show produk in orederitem, please helping me to show orderitem :v. I am really newbie in here .
models.py
class Order(models.Model):
name = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True)
order_data = models.DateTimeField(auto_now_add=True)
selesai = models.BooleanField(default=False, blank=True, null=True)
status = models.BooleanField(default=False, blank=True, null=True)
id_transaksi = models.CharField(max_length=200, null=True)
bukti = models.ImageField(null=True, blank=True)
ongkir = models.CharField(max_length=200, null=True)
total = models.CharField(max_length=200, null=True)
total_harga = models.CharField(max_length=200, null=True)
pembayaran = models.CharField(max_length=200, null=True)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0)
date_added = models.DateTimeField(auto_now_add=True)
views.py
def pembayaran(request):
customer = request.user.profile
ido = Order.objects.filter(id)
orders = Order.objects.filter(name=customer, selesai=True)
pengiriman = Pengiriman.objects.filter(name=customer)
OrderItems = OrderItem.objects.filter(order=ido)
print(OrderItems)
context = {'orders': orders,'pengiriman' :pengiriman , 'OrderItems': OrderItems }
return render(request, 'store/pembayaran.html', context)
I´m trying to filter a queryset with a ForeignKey field but I get the following error:
Cannot resolve keyword 'workflowcontenidos' into field. Choices are:
categoria_producto, descripcion_brief, descripcion_long, estatus_contenido,
estatus_contenido_id, foto_1, foto_2, id, perfil_cliente, productosbase, usos,
video
My models are:
class WorkflowContenidos(models.Model):
estatus = models.CharField(max_length=200, help_text="Estatus de contenido", blank=False, null=True)
def __str__(self):
return str(self.estatus)
class Categorias_Producto(models.Model):
categoria_producto = models.CharField(max_length=50, help_text="Catergoría de producto", unique=True, blank=False, null=True)
descripcion_brief = models.TextField(max_length=200, help_text="Descripción resumida", blank=True, null=True)
descripcion_long = models.TextField(max_length=500, help_text="Descripción extendida", blank=True)
usos = models.CharField(max_length=200, help_text="Usos (separados por comas)", blank=True, null=True)
foto_2 = models.ImageField(upload_to='', default="", blank=False, null=False)
foto_1 = models.ImageField(upload_to='', default="", blank=False, null=False)
video = models.URLField("Link brand video", max_length=128, blank=True, null=True)
perfil_cliente = models.CharField(max_length=200, help_text="Perfil de cliente", blank=True, null=True)
estatus_contenido = models.ForeignKey("WorkflowContenidos", help_text="Estatus del contenido", blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return str(self.categoria_producto)
The "estatus" values in the WorkflowContenidos model are:
Incompleto
Revisión
Aprobado
The view:
def WorkflowContenidosView(request):
lista_visualizacion = Categorias_Producto.objects.filter(workflowcontenidos__estatus='Incompleto')
return render(request, 'catalog/content-workflow.html', {
'lista_visualizacion': lista_visualizacion
})
lista_visualizacion = Categorias_Producto.objects.filter(estatus_contenido__estatus='Incompleto')
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']