Django foreign key question
-
22-09-2019 - |
Question
All,
i have the following model defined,
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
class options(models.Model):
opt_details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
AND IN MY VIEWS I HAVE
p= header(title=name,created_by=id)
p.save()
Now the data will be saved to header table .My question is that for this id generated in header table how will save the data to criteria and options table..Please let me know..
Thanks..
Solution
Given your:
p= header(title=name,created_by=id)
p.save()
You can now:
c=criteria(details='some details', headerid=p)
c.save()
o=options(opt_details='more details', headerid=p)
o.save()
Hope this helps.
OTHER TIPS
Take advantage of <related>_set
query managers, it's clearer and shorter than constructing and saving objects in separate operations.
h = header.objects.create(title=name,created_by=id)
c = h.criteria_set.create(details='some details')
o = h.options_set.create(opt_details='more details')
And some offtopic: please, start class names from uppercase letter, it really makes code easier to read.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow