Django Foreign Key - mysql

I am trying to generate a report across 2 models/ tables. Here they are:
class Members(models.Model):
username = models.CharField(max_length=30,null=True, unique=True)
email = models.CharField(max_length=100,null=True, unique=True)
name = models.CharField(max_length=30,null=True)
phone = models.CharField(max_length=30,null=True)
and
class Report(models.Model):
report_text = models.CharField(max_length=500)
reporter_id = models.IntegerField(db_index=True)
reported_id = models.IntegerField(db_index=True)
date_created = models.DateTimeField(null=True)
date_read = models.DateTimeField(null=True)
The 2 tables obviously have auto increment IDs as the primary key.
The report will look like this:
Reported Phone | Reported Name | Report | Date Reported | Date Report Read
Everyone reported on will be in the member table. The reporter ID is the ID of the member who logged the report. The reported_id is the ID of the person the report is on. I need to do a join across the 2 models to get the members name and their phone number. I can't quite work it out form the doc. I believe I should make the reported_id and reporter_id both foreign keys to the Members table primary key ID field. How do I do that and what code will extract the report for all entries submitted by a specific reporter?
Do I user reported_id = models.ForeignKey(Members) and do the same for reporter_id. It seems odd as I don't specify the field that the field is foreign to. The ORM is supposed to make it easier (and it usually does!). I could do it with a join in SQL but this has got me stumped.
I hope the question makes sense.
Thanks in advance
Rich

How do I do that and what code will
extract the report for all entries
submitted by a specific reporter?
Yes, do reported_id = models.ForeignKey(Members)
The field will be the target models primary key, which is in your case id since you haven't specified one.
You will need to specify a related_name for one of these fields to prevent a name clash for the reverse foreign key accessor.
After setting up the foreign key field, to get all objects related via that foreign key, use the related_name to query the related model.
http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
For example, if you set up your model as:
reporter = models.ForeignKey(Members, related_name="reports_by_me")
reported = models.ForeignKey(Members, related_name="reports_by_others")
You could access all related Report models via that foreign key by
member_instance.reports_by_me.all()
member_instance.reports_by_others.all()

Related

Django CharField as primary key still allow Null value to be save

Currently i have the following model that i would like to set CharField as primary key( my database is Mysql)
class Customer(models.Model):
class Meta:
db_table = "customers"
verbose_name = _('Customer')
verbose_name_plural = _('Customers')
customer_id = models.CharField(_('Customer ID'),max_length=255, primary_key=True)
name = models.CharField(_('Name'), max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
In the document it stated that :
primary_key=True implies null=False and unique=True. Only one primary
key is allowed on an object.
In Mysql the primary key has the following structure:
customer_id, type=varchar(255), collation=latin1_swedish_ci,
Attributes=blank Null=No, Default=None,Comments=blank, Extra=blank
but when i try to use the save() method with null value for primary key:
Customer.objects.create(customer_id=None, name="abc")
It still save Null value in the primary key without returning any error or validation, why is that?
EDIT:
After saving in Mysql it show the value of the customer_id=blank(when try to save it as None). Why it set to blank when saving customer_id=None?
When you create object for the first time
Customer.objects.create(customer_id=None, name="abc")
It will store customer_id value as '' (empty value, not null) and there are no other object we have created till now, so it's unique too.
Now when you again create an Customer object
Customer.objects.create(customer_id=None, name="xyz")
This will throw an error django.db.utils.IntegrityError: UNIQUE constraint failed: customers.customer_id because we already have empty value in our customer_id value. So, this is throwing an error of UNIQUE constraint
Do you use Django Rest Framework?
Then you may have add your customer_id to the read_only_fields in serializer.py
The result is:
You can't add an id in your request
Django doesn't recognised it as a required field anymore (except of Django Admin)
Django accepts a NULL value, which shouldn't be allowed

Foreign Key Prefix to Auto_Increment Primary Key (INT)

Skip down for TL:DR version
Currently designing a Horse-riding class booking function for a Club's website.
Designing the SQL database from scratch using phpMyAdmin. Members join the club as per family basis - Meaning each unique "Family_ID" would contain multiple members within each one.
The club only wants users to login with their Family_ID and through that one login the user would be able to book a riding class for any of the members within the family. was wondering if it's possible to give each member a unique ID by referencing the Foreign Key (Family_ID). So each member would have a unique ID based on their Family_ID. Example Listed below.
When a new family registers for the club - they fill in paper forms which an admin will enter their details into the existing database, currently the members don't have an ID, just details kept within each Family_ID. Was thinking of a work-around where when a new member is being added the form would have an auto-fill input box that adds '01'/'02'/etc to the ends of family_id.
TL:DR
SQL - phpMyAdmin
Multiple Members within a "Family_ID"
Multiple Members share a "Family_ID" (Foreign Key from "Family" Table)
Each Member to have a Unique ID - "Member_ID" (That uses the Family_ID as a prefix)
Example
Family_ID = 0024
Member_ID = 002401 (Unique Member_ID Auto_increment using last two digits)
My first post so I apologize if I left out any necessary information, Thank you for your answers.

Django / MYSQL foreign key best practice

I have three models:
class Agent(models.Model):
name = models.CharField(max_length=200)
class Phone(models.Model):
calls = models.CharField(max_length=200)
agent_phone_name = models.CharField(max_length=200)
agent = models.ForeignKey(Agent, on_delete=models.CASCADE)
class Chat(models.Model):
chats = models.CharField(max_length=200)
agent_chat_name = models.CharField(max_length=200)
agent = models.ForeignKey(Agent, on_delete=models.CASCADE)
Chat and Phone links to agent with foreign key.
I want to make a table like this:
agent1 | sum(calls) | sum(chats)
agent2 | sum(calls) | sum(chats)
agent3 | sum(calls) | sum(chats)
First question is:
I've read about SQL foreign key as a way to maintain data and referential integrity. However in my case, there are miss call and chat (agent didn't pick it up) that generate rows of data has empty value on agent_name. So when I'm inserting the phone/chat data and update the FK, I have leave the FK empty and kinda that conflicts with the idea of FK. What's the best way to handle this?
Second question is: is using Foreign key the only way to perform SQL join table query in Django ORM? Is there any other way around it?
Thank you !

Multiple primary & foreign keys Access

I am using Access 2007.
Tables:
- Budget Lines (project_id (PK), donor_code (PK), ...)
- Contracts (project_id (FK), donor_code (FK), ...)
PK = Primary Key
FK = Foreign Key
Let's say that I have entered the field project_id in the table Contracts, and I now want to enter the field donor_code: what do I need to do to make sure that I can only choose among the donor_codes that are combined with the project_id that I entered and not all the existing budget codes ?
Well, having 2 fields as primary key has always looked awkward to me.
My suggestion would be to add an autonumber field in your budget_lines table and declare it as the primary key. Then, you can index the 2 other fields to ensure that there are no duplicates.
As far as I understand, you have a Project table and a Donor table which are both linked to the budget lines table. And then you want to link these buddget lines to contracts.
If you input the data directly in the table, I can't seem to find a solution. Still if you input them through a form, with a little of VBA some workarounds can be found.
One way would be to use the after_update event of your combo boxes for ProjectID and Donor_Code to modify the row source of the query of the other combo box of the pair.
The code would look something like that :
Private Sub ProjectID_AfterUpdate()
If Me!ProjectID.Value Is Null Then
Me.DonorCode.RowSource = "SELECT BudgetLines.Donor_Code, BudgetLines.Whatever >FROM BudgetLines;"
Else
Me.DonorCode.RowSource = "SELECT BudgetLines.Donor_Code, BudgetLines.Whatever FROM BudgetLines WHERE BudgetLines.ProjectID= " & [Me]![ProjectID] & ";"
End If
End Sub

How to make proper use of foreign keys

I'm developing a helpdesk-like system, and I want to employ foreign keys, to make sure the DB structure is decent, but I don't know if I should use them at all, and how to employ them properly.
Are there any good tutorials on how (and when) to use Foreign keys ?
edit The part where I'm the most confused at is the ON DELETE .. ON UPDATE .. part, let's say I have the following tables
table 'users'
id int PK auto_increment
department_id int FK (departments.department_id) NULL
name varchar
table 'departments'
id int PK auto_increment
name
users.department_id is a foreign key from departments.department_id, how does the ON UPDATE and ON DELETE functions work here when i want to delete the department or the user?
ON DELETE and ON UPDATE refer to how changes you make in the key table propagate to the dependent table. UPDATE means that the key values get changed in the dependent table to maintain the relation, and DELETE means that dependent records get deleted to maintain the integrity.
Example: Say you have
Users: Name = Bob, Department = 1
Users: Name = Jim, Department = 1
Users: Name = Roy, Department = 2
and
Departments: id = 1, Name = Sales
Departments: id = 2, Name = Bales
Now if you change the deparments table to modify the first record to read id = 5, Name = Sales, then with "UPDATE" you would also change the first two records to read Department = 5 -- and without "UPDATE" you wouldn't be allowed to make the change!
Similarly, if you deleted Department 2, then with "DELETE" you would also delete the record for Roy! And without "DELETE" you wouldn't be allowed to remove the department without first removing Roy.
You will need foreign keys if you are splitting your database into tables and you are working with a DBMS (e.g. MySQL, Oracle and others). I assume from your tags you are using MySQL.
If you don't use foreign keys your database will become hard to manage and maintain. The process of normalisation ensures data consistency, which uses foreign keys.
See here for foreign keys. See here for why foreign keys are important in a relational database here.
Although denormalization is often used when efficiency is the main factor in the design. If this is the case you may want to move away from what I have told you.
Hope this helps.