Reputation: 100
In Django I want to query the records in all tables that have the foreign key project = ProjectMain's chosen pk. So if I choose a record in ProjectMain and it's pk=2 I also want the records from the other three tables where the foreign key product=2.
Tables Methods, Things, and MoreStuff can have multiple records with project=2.
Here are the tables:
class ProjectMain(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.CharField(max_length=60)
product = models.ForeignKey(ProductType, on_delete=models.CASCADE)
filler = models.CharField(max_length=100)
class Methods(models.Model):
method_name = models.CharField(max_length=10)
method_test = models.CharField(max_length=50, null=False)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)
class Things(models.Model):
thing1 = models.CharField(max_length=10)
thing2 = models.CharField(max_length=50, null=False)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)
class MoreStuff(models.Model):
stuff1 = models.CharField(max_length=10)
stuff2 = models.CharField(max_length=50, null=False)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)
I've been trying Django querysets and am getting nowhere. Please help.
Upvotes: 0
Views: 759
Reputation: 13731
You can access them via the related_name
property as defined in ForeignKey.
project_main = ProjectMain.objects.get(id=2)
methods = project_main.methods_set.all() # All the Methods related to the instance
things = project_main.things_set.all() # All the Methods related to the instance
more_stuffs = project_main.morestuff_set.all() # All the Methods related to the instance
Upvotes: 1