I have 2 models Parent
, Child
class Parent(models.Model):
description = models.CharField(max_length=250, null=True, blank=True)
child_list = models.CharField(max_length=250, null=True, blank=True)
class Child(models.Model):
price = models.CharField(max_length=250, null=False, blank=False)
I need to populate child_list
whenever a Child object is created
I don't know if there is a predefined tool in Django for that, the goal is basically for each 'parent' to know how many children it has (with a list of the ids of its children).
What I had thought was to create a list with the ids of the children, but I think it is not efficient/elegant at all.
Does anyone know what would be the right way to do it?
CodePudding user response:
Like @dudulu said, you can use foreign keys for this.
Example:
class Faq(models.Model):
name = models.CharField(max_length=255, default='none')
email = models.CharField(max_length=255, default='none')
subject = models.CharField(max_length=255, default='none')
date = models.DateField(auto_now_add=True)
def __str__(self):
return self.subject
def get_absolute_url(self):
return reverse("faq_detail", kwargs={"pk": self.pk})
class Answers(models.Model):
faqs = models.ForeignKey(
"Faq", on_delete=models.CASCADE, null=True, related_name='answers')
detail = models.TextField()
date = models.DateField(auto_now_add=True, null=True)
Or something of the like.
This website on foreign keys helped me alot when I tried it myself.
CodePudding user response:
This should be what you want, this is the simplest example.
You should try to google django ForeignKey example.
First
class Parent(models.Model):
description = models.CharField(max_length=250, null=True, blank=True)
class Child(models.Model):
price = models.CharField(max_length=250, null=False, blank=False)
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
First for
for p in Parent.objects.all():
print(f'count: {p.child_set.count()}')
for child in p.child_set.all():
print(f'child: price: {child.price}')
Second
class Child(models.Model):
price = models.CharField(max_length=250, null=False, blank=False)
parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name='custom_child')
Second for
for p in Parent.objects.all():
print(f'count: {p.custom_child.count()}')
for child in p.custom_child.all():
print(f'child: price: {child.price}')
Simply take the ID List...
for p in Parent.objects.all():
id_list = [child.id for child in p.custom_child.all()]