Sample model
class Chapter(models.Model):
name = models.CharField(max_length=100)
tags = models.ManyToManyField(Tag, blank=True, null=True)
Create Relationship - One by One
new_chapter = Chapter.objects.create(name=chapter_name)
new_tag = Tag.objects.create(name=tag_name)
new_chapter.tags.add(new_tag)
Create Relationship - Multiple
new_section = Section.objects.create(name=section_name, chapter=parent_chapter)
new_section.tags = list(parent_chapter.tags)
Iterate ManyToMany relationship
for tag in parent_chapter.tags.all():
new_section.tags.add(tag)
ไม่มีความคิดเห็น:
แสดงความคิดเห็น