Let’s say I have these two models (in models.py file):
class FullName (models.Model): firstName = models.CharField(max_length=30,null=True,blank=False,unique=True) lastName = models.CharField(max_length=30,null=True,blank=False,unique=True) class Address (models.Model): addressLine = models.CharField(max_length=30,null=True,blank=False) city = models.CharField(max_length=30,null=True,blank=False) state = models.CharField(max_length=30,null=True,blank=False) zipcode = models.CharField(max_length=30,null=True,blank=False)
How can I merge these two models in a new model but with the same Id? So it becomes:
class FullName (models.Model): firstName = models.CharField(max_length=30,null=True,blank=False,unique=True) lastName = models.CharField(max_length=30,null=True,blank=False,unique=True) class Address (models.Model): addressLine = models.CharField(max_length=30,null=True,blank=False) city = models.CharField(max_length=30,null=True,blank=False) state = models.CharField(max_length=30,null=True,blank=False) zipcode = models.CharField(max_length=30,null=True,blank=False) class AllInformation (models.Model): firstName = models.CharField(max_length=30,null=True,blank=False,unique=True) lastName = models.CharField(max_length=30,null=True,blank=False,unique=True) addressLine = models.CharField(max_length=30,null=True,blank=False) city = models.CharField(max_length=30,null=True,blank=False) state = models.CharField(max_length=30,null=True,blank=False) zipcode = models.CharField(max_length=30,null=True,blank=False) (all fields should be inherited from FullName and Address models)
PS: In my views.py file I called a save method like that:
fullNameData = FullName(request.POST) fullNameData.save() and AddressData = Address(request.POST) AddressData.save()
Thanks in advance and I really appreciate who answers that because I see that many people having the same problem. I also took a look at the OneToOneField from django docs but I understood nothing to be honest xD
Advertisement
Answer
Solution:
When submitting the FullName form I just do:
data = AllInformation(firstName = request.POST.get("firstname"), lastName = request.POST.get("lastname")) data.save()
Then in the 2nd function when submitting the Address form, I just do:
AllInformation.objects.filter(firstName=the first name got from FullName Form).update(addressLine = value, city = value, ... )
Hope it helps anyone who is trying to merge two (or more) models in one other model that should contain all of the previous model fields.