'How can we add more than 3 authors field for a single magzine? in Django models
I created a magzine model in django. But their are more than three authors of a magzine. I have written below code for three authors. If I write the code of two or three author for a single magzine then it is looks somewhat good. But if I make for more than three authors then it will looks very bad. Now I am confused, Is the method that I have created is wrong? And if it is wrong then how should I write it?
author_name1 = models.CharField(max_length=300, blank=True)
designation1 = models.CharField(max_length=100, blank=True)
author_pic1 = models.ImageField(upload_to="authorpic", blank=True)
author_detail1 = models.TextField(max_length=1000, blank=true)
author_name2 = models.CharField(max_length=300, blank=True)
designation2 = models.CharField(max_length=100, blank=True)
author_pic2 = models.ImageField(upload_to="authorpic", blank=True)
author_detail2 = models.TextField(max_length=1000, blank=true)
author_name3 = models.CharField(max_length=300, blank=True)
designation3 = models.CharField(max_length=100, blank=True)
author_pic3 = models.ImageField(upload_to="authorpic", blank=True)
author_detail3 = models.TextField(max_length=1000, blank=true)
Solution 1:[1]
You can make an extra model Author
with a ForeignKey
[Django-doc] to Magazine
. If the same Author
can write multiple Magazine
s, you might want to use a ManyToManyField
[Django-doc] instead:
class Author(models.Model):
name = models.CharField(max_length=300, unique=True)
designation = models.CharField(max_length=300, blank=True)
picture = models.ImageField(upload_to_authorpic, blank=True)
detail = model.TextField(max_length=1000, blank=True)
class Magazine(models.Model):
# …
authors = models.ManyToManyField(
Author,
related_name='magazines',
on_delete=models.CASCADE
)
You probably want to make name
a unique=True
[Django-doc] field to avoid creating two Author
objects with the same name.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |