One to Many relationships in DJANGO - how to generate a row of uniqueness based on 2 compound keys
I am trying to create a relationship based on a compound key based on 2 fields for uniqueness. From my understanding Django uses foreign keys to define one to many relationships?
This is my scenario:
I have 2 tables
Table1
Table2
I want to write code to generate rows for Table3 records which iterate through Table 2 and generate the list below and generate the compound key combination:
I want to create this relationship using models.py, however, every time I save a record the ID in table 2 increments
see example of Table 2
How can I force this behaviour?
This is the code I have used
Table1 is Parish i derive the value for parish.id
Table2 is CheckList.object.all()
Table3 is All_Inpection
def form_valid(self, form):
form.instance.author = self.request.user
parish = form.save(commit=False)
parish.user_id = self.request.user.id
parish.save()
entry = Company.objects.get(pk=parish.id)
Checklists = Checklist.objects.all()
for rec in Checklists:
new_rec=All_Inspection(str_status=rec.str_status, str_comment='',company_id=entry)
new_rec.save()
return super().form_valid(form)
The short answer is - right now at least - you can't do this. Django ForeignKey
works on the primary key of another table, and you cannot have a composite primary key.
The longer answer involves a couple of options.
Option 1
Wait until ticket #373 is merged in ... this will provide composite PK functionality for django, and you can do exactly as you like.
Option 2
Forget about composite pks. Set up a unique_together
index on the table to ensure uniqueness, and use an integer or uuid key field, which will be the value in your FK field. The only thing you will lack here is the actual compound key values on the parent table, because that will hold the int/uuid value instead.
Edit: I remembered after writing this that unique_together
is deprecated in favour of UniqueConstraint
. Same thing, but if you're on a "modern" version of Django you should use that.