I'm trying to make auto field like that for invoice which is either part of customers table or invoice table it is okay in the 2 sitautions
the format I want like this Year-Month-auto depends on the number before it
for example : 202201-001 the first one , 202205-504 like that and it's auto generted once I create new customer
model.py
class customer(models.Model):
cust_id = models.BigAutoField(auto_created = True , primary_key=True, editable=False)
package = models.FloatField()
DOJ = models.DateField()
payment = models.IntegerField()
receipt = models.ForeignKey('receipt', on_delete=models.SET_NULL, null= True, blank=True)
balance = models.FloatField(null = True)
enq_id = models.ForeignKey('enquiry', on_delete=models.SET_NULL, null= True, blank=True)
lead_id = models.ForeignKey('lead', on_delete=models.SET_NULL, null= True, blank=True)
I'm trying to make full auto id for my invoices so I can use in my view
Related
models.py
So,here i want to make Invoicemgmt model in which i can have multiple entries for Invoice table having
customer,project and Invoice_amount.
Basically,requirement is that whenever i see 'view_Invoice' of some id,first i will see all data of that
specific id on that page and then i want to have small table below for invoice_mgmt,where i can add amount received for that specific id invoice.
*so,i want to know what fields should i add in invoice_mgmt model for relationship "
class Invoice(models.Model):
company_choice = (
('VT_India', 'VT_India'),
('VT_USA', 'VT_USA'),
)
company = models.CharField(
max_length=30, blank=True, null=True, choices=company_choice)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
project = models.ForeignKey(Allproject, on_delete=models.CASCADE)
invoice_title = models.CharField(max_length=15)
invoice_id = models.IntegerField(primary_key=True)
invoice_amount = models.IntegerField()
invoice_date = models.DateField(
blank=True, null=True)
invoice_duedate = models.DateField(
blank=True, null=True)
invoice_description = models.TextField()
def __str__(self):
return self.invoice_title
class Paymentmethod(models.Model):
paymentmethod_id = models.IntegerField(primary_key=True)
paymentmethod_name = models.CharField(max_length=15)
def __str__(self):
return self.paymentmethod_name
class Invoicemgmt(models.Model):
invoicemanagement_id = models.IntegerField(primary_key=True)
invoice_received = models.IntegerField()
date = models.DateField(
blank=True, null=True)
payment_method = models.ForeignKey(Paymentmethod, on_delete=models.CASCADE)
"So, basically i want to have multiple entries in invoice mgmt table for one specific invoice table id(one specific data)"
Basically I want to use 'chartjs' for display "Clustered Bar chart", with following things year wise
Total amount
Amount Received
Amount Left
I want to fetch data from data base and display it on chart, I have saved data of all above field 3 fields in one table for each date and I want to also fetch year from Datefield.
Main things is how to display Clustered bar chart by fetching data from database for each year.
class Allinvoice(models.Model):
company_choice = (
('VT_India', 'VT_India'),
('VT_USA', 'VT_USA'),
)
company = models.CharField(
max_length=30, blank=True, null=True, choices=company_choice)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
project = models.ForeignKey(Allproject, on_delete=models.CASCADE)
invoice_title = models.CharField(max_length=15)
invoice_id = models.IntegerField(primary_key=True)
currency = models.ForeignKey(Currency, on_delete=models.CASCADE)
invoice_amount = models.IntegerField()
invoice_date = models.DateField(
blank=True, null=True)
invoice_duedate = models.DateField(
blank=True, null=True)
invoice_description = models.TextField()
def __str__(self):
return str(self.invoice_id)
class Paymentdete(models.Model):
payment_id = models.IntegerField(primary_key=True)
invoice = models.ForeignKey(
Allinvoice, on_delete=models.CASCADE)
total_amount = models.IntegerField()
amountreceived = models.IntegerField()
amount_left = models.IntegerField()
currency = models.ForeignKey(Currency, on_delete=models.CASCADE, null=True)
date = models.DateField(
blank=True, null=True)
paymentmethod = models.ForeignKey(
Allpaymentmethod, on_delete=models.CASCADE)
def __str__(self):
return str(self.payment_id)
So, above is the code of my 2 models.So, i want to get total of all data yearwise for example
for year 2019= Total Amount,Amount Received,and amount Left
for year 2020= Total Amount,Amount Received,and amount Left
...etc...
for all years in form of clustered Bar Chart
You do it like this for a field called date:
dates = Paymentdete.objects.filter(date__year='2021')
I'm struggling to find documentation and examples to solve the following dilemma. I have two tables, Results (which contain results of a race) and Photos (where each photo contain runners in that race). Both tables contain entrant_numbers, i.e. the number of the runner in the race and the number of the runner in the photo. In SQL I joined them like so to get the total number of photo captures per runner.
SELECT * FROM Photo p
INNER JOIN Result r ON p.entrant_number=r.entrant_number AND p.race_year=r.race_year
WHERE r.user_id=123
My models are structured like so;
class Photo(models.Model):
photo_id = models.AutoField(primary_key=True)
race_id = models.ForeignKey('Race')
url_pre_string = models.CharField("URL pre-string", max_length=255)
filename = models.CharField("Filename", max_length=100)
extension = models.CharField("File extensions", max_length=4)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
class Race(models.Model):
race_id = models.AutoField(primary_key=True)
race_year = models.PositiveIntegerField("Race year", null=False, blank=False)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
class Result(models.Model):
result_id = models.AutoField(primary_key=True)
race_id = models.ForeignKey('Race')
position = models.PositiveIntegerField("Position", default=0)
entrant_number = models.PositiveIntegerField("Entrant number", default=0, null=True, blank=True)
user_id = models.ForeignKey(User, null=True)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
The most recent query I tried was;
photo_captures = Photo.objects.filter(result__user_id_id=current_user.id)
I was hoping this would traverse back through result and filter on the current user id.
You can join two tables by performing a raw SQL query.
You can check how to do this here
from django.db import connection
def my_custom_sql(self):
cursor = connection.cursor()
cursor.execute("select *
from myapp_photo p
inner join myapp_result r ON
p.entrant_number=r.entrant_number AND
p.race_year=r.race_year
WHERE r.user_id=123")
row = cursor.fetchone()
return row
Alternate way:
You can set foreign key in Photo model to Result model, following this you will have unique photos of the different results. Something like this :
class Result(models.Model):
results_id = models.AutoField(primary_key=True)
position = models.PositiveIntegerField("Position", default=0)
entrant_number = models.PositiveIntegerField("Entrant number", default=0, null=True, blank=True)
race_year = models.PositiveIntegerField("Race year", default=0)
user_id = models.ForeignKey(User, null=True)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
class Photo(models.Model):
result= models.ForeignKey(Result)
photo_id = models.AutoField(primary_key=True)
url_pre_string = models.CharField("URL pre-string", max_length=255)
filename = models.CharField("Filename", max_length=100)
extension = models.CharField("File extensions", max_length=4)
entrant_number = models.PositiveIntegerField("Entrant number", default=0, null=True, blank=True)
race_year = models.PositiveIntegerField("Race year", default=0)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
and then to fetch the photos for a particular result of year for a single user you can do
photos = Photo.objects.filter(entrant_number = result__entrant_number,
race_year = result__race_year,
result__user_id = 123)
ofcourse i haven't tested this but this should do the trick. let me know if this works or if you need any help.
I receive 6 weekly excel reports that I've been manually compiling into a very large monthly report. Each report has between 5-30 columns, and 4000 to 130,000 rows.
I'm putting together a simple Django app that allows you to upload each report, and the data ends up in the database.
Here's my models.py:
#UPEXCEL models
from django.db import models
############## LISTS ###############
class TransactionTypeList(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class TransactionAppTypeList(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class CrmCaseOriginList(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
############## CLIENTS AND STAFF ###############
class Staff(models.Model):
name = models.CharField(max_length=40)
employee_id = models.CharField(max_length=40)
start_date = models.TimeField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
first_name = models.CharField(blank=True, null=True, max_length=40)
last_name = models.CharField(blank=True, null=True, max_length=40)
email = models.EmailField(blank=True, null=True)
phone = models.CharField(blank=True, null=True, max_length=20)
street = models.CharField(blank=True, null=True, max_length=100)
city = models.CharField(blank=True, null=True, max_length=100)
state = models.CharField(blank=True, null=True, max_length=2)
zipcode = models.CharField(blank=True, null=True, max_length=10)
is_team_lead = models.BooleanField(default=False)
boss = models.ForeignKey('Staff', related_name='Boss', null=True, blank=True)
def __str__(self):
return self.name
class Meta:
app_label="upexcel"
class Client(models.Model):
name = models.CharField(max_length=40)
short_name = models.CharField(max_length=20, blank=True, null=True)
start_date = models.DateField(default=timezone.now, blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
team_lead = models.ForeignKey(Staff, related_name='client_team_lead')
def __str__(self):
return self.name
class ClientNameChart(models.Model):
client_name = models.ForeignKey(Client, related_name='client_corrected_name')
name_variation = models.CharField(max_length=100)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s becomes %s' % (self.name_variation, self.client_name)
class StaffNameChart(models.Model):
staff_name = models.ForeignKey(Staff, related_name='staff_corrected_name')
name_variation = models.CharField(max_length=100)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s becomes %s' % (self.name_variation, self.staff_name)
############## DATA FROM REPORTS ###############
class CrmNotes(models.Model):
created_by = models.ForeignKey(Staff, related_name='note_creator')
case_origin = models.CharField(max_length=20)
client_regarding = models.ForeignKey(Client, related_name='note_client_regarding')
created_on = models.DateTimeField()
case_number = models.CharField(max_length=40)
class Transactions(models.Model):
client_regarding = models.ForeignKey(Client, related_name='transaction_client')
created_by = models.ForeignKey(Staff, related_name='transaction_creator')
type = models.ForeignKey(TransactionTypeList, related_name='transaction_type')
app_type = models.ForeignKey(TransactionAppTypeList, related_name='transaction_app_type')
class Meta:
app_label="upexcel"
class Timesheets(models.Model):
staff = models.ForeignKey(Staff, related_name='staff_clocked_in')
workdate = models.DateField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
total_hours = models.DecimalField(decimal_places=2, max_digits=8)
class Provider(models.Model):
name = models.CharField(max_length=40)
street = models.CharField(max_length=100)
city = models.CharField(max_length=40)
state = models.CharField(max_length=11)
zip = models.CharField(max_length=10)
class StudentsApplication(models.Model):
app_number = models.CharField(max_length=40)
program = models.CharField(max_length=40)
benefit_period = models.CharField(max_length=40)
student_name = models.CharField(max_length=40)
student_empl_id = models.CharField(max_length=40)
requested_amount = models.DecimalField(max_digits=8, decimal_places=2)
provider = models.ForeignKey(Provider, related_name='app_provider')
provider_code = models.CharField(max_length=40)
class AuditReport(models.Model):
was_audited = models.BooleanField(default=False)
auditor = models.ForeignKey('upexcel.Staff', related_name='auditor')
payment_defect = models.BooleanField(default=False)
grant_discount_error = models.BooleanField(default=False)
math_error = models.BooleanField(default=False)
fees_book_error = models.BooleanField(default=False)
other_error = models.BooleanField(default=False)
overpayment_amount = models.DecimalField(max_digits=8, decimal_places=2)
underpayment_amount = models.DecimalField(max_digits=8, decimal_places=2)
doc_defect = models.BooleanField(default=False)
status_change = models.BooleanField(default=False)
admin_savings_defect = models.BooleanField(default=False)
network_savings_defect = models.BooleanField(default=False)
admin_adjustments = models.DecimalField(max_digits=8, decimal_places=2)
network_adjustments = models.DecimalField(max_digits=8, decimal_places=2)
error_corrected = models.BooleanField(default=False)
comments = models.TextField(max_length=500)
client = models.ForeignKey(Client, related_name='audited_client')
staff = models.ForeignKey(Staff, related_name='processor_audited')
application = models.ForeignKey(StudentsApplication, related_name='app_audited')
class Meta:
app_label="upexcel"
However the excel reports I'm taking in need some work done to them, and I'm trying figure out exactly how I should go about processing them and routing them.
The first challenge is that each report references the associated Staff and Client with different data. For example, if the Staff.name is "Bob Dole", one report has it as "Dole, Bob". Another has it as "Dole, Robert". Still another has "Robert Dole" then "103948210", which is his employee ID number.
Also, these change and new ones sprout up, which is why I made ClientNameChart and StaffNameChart, to where a user can input the string as it shows up in a report, and attach it to a Client or Staff. Then when processing, we can lookup StaffNameChart.name_variation, and return the associated StaffNameChart.Staff.employee_id, which should work great as a foreign key within the respective report's table (ie. AuditReport.staff)
The second challenge is to take a report, and route some of the columns to one database table, and others to another. For example, the big one is the Audit Report sheet. Many of the columns just transpose directly into the AuditReport(models.Model). However, it also has data for each StudentsApplication and Provider, where I need to take several columns, store them as a new record in their destination table, and replace the columns with one column containing a foreign key for that item within that destination table.
So that is my quest.
Here's the order of operations I have in my head - I will use the most complex Audit_Report_Wk_1.xlsx report to address all challenges in one upload:
Upload File
Using openpyxl, load read-only data:
from openpyxl.worksheet.read_only import ReadOnlyWorksheet
myexcelfile = request.FILES['file']
myworkbook = load_workbook(myexcelfile, read_only=True)
mysheet = myworkbook['Sheet1']
Write a script that matches the names strings of the staff, auditor, and client columns with StaffNameChart.name_variation, and replace it with StaffNameChart.Staff.name.
Part B: If the client or staff columns are blank, or contain strings not found in the name charts, all of those rows get saved in a new excel document. Edit: I suppose I could also create a new model class called IncompleteAuditReport that just have fields that match up with each column and store it there, then if someone adds a new NameChart variation, it could trigger a quick look-up to see if that could allow this process to complete and the record to be properly added?)
Check the columns in mysheet that will be replaced by foreign keys for the Provider and StudentsApplication tabes. If their respective data doesn't yet exist in their respective tables, add the new record. Either way, then replace their columns with the foreign key that points to the resulting record.
Is this the correct order of operations? Any advice on what specific tools to use from openpyxl etc. to manipulate the data in the most efficient ways, so I can use the fewest resources possible to look-up and then change several hundred thousand fields?
Thank you so much if you've read this far. I'm currently a bit intimidated by the more complex data types, so it's not crystal clear to me the best way to store the data in memory and to manipulate it while it's there.
I am trying to create a lyrics app in Django. And I have come up with this model. The site will be community based, that is people will submit lyrics once they input the proper captcha challenge etc.. That comes at a price I guess, for example how can I enforce the relationship between Song and Album?
But most importantly is my design sound? Is there a need for more models?
class Artist(models.Model):
first_name = models.CharField(max_length=50, null = False, blank = True)
middle_name = models.CharField(max_length=50, null = True, blank = True)
last_name = models.CharField(max_length=50, null = True, blank = True)
biography = models.TextField(null=True, blank = True)
comment = models.TextField(null=True, blank = True)
thumb = models.BinaryField(null=True, blank = True)
num_stars = models.IntegerField(default=0, blank = True)
class Lyrics(models.Model):
artist = models.ForeignKey(Artist)
title = models.CharField(max_length=100)
lyrics_content = models.TextField(null = False, blank=True)
comment = models.TextField(null=True, blank=True)
num_stars = models.IntegerField(default=0, blank = True)
song_language = models.CharField(max_length=50, null = True, blank=True)
class Song(models.Model):
artist = models.ForeignKey(Artist)
album = models.ForeignKey(Album)
name = models.CharField(max_length=100)
release_date = models.DateField(null = True, blank=True)
num_stars = models.IntegerField(default=0, blank=True)
song_file = models.TextField(null=True, blank=True)
class Album(models.Model):
artist = models.ManyToManyField(Artist)
name = models.CharField(max_length=100)
release_date = models.DateField(null = True, blank=True)
num_stars = models.IntegerField(default=0, blank=True)
At a quick glance, most things look OK.
In terms of the relationship between Song and Album, I would expect 1 song to be able to appear on more than one Album, so maybe a M2M relation there?
Also, songs could be performed by many Artists (original + several covers), so that relationship could probably be worked on in terms of flexibility, unless you want to treat a cover as a unique song - but then you get repetition of Lyrics, right?
Finally, I'm guessing the thumb field is to hold an image, so maybe that could be an ImageField?