Many-to-many relationships
To define a many-to-many relationship, use ManyToManyField.
Example: "models.py"
from django.db import models
class Publisher(models.Model):
idno = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
class Article(models.Model):
idno = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
pub = models.ManyToManyField(Publisher)
app/forms.py
from django import forms
from .models import Publisher,Article
class PublisherForm(forms.ModelForm):
class Meta:
model = Publisher
fields = "__all__"
labels = {"name":"NAME"}
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = "__all__"
labels = {"name":"NAME","pub":"PUBLISHER"}
To Save the Details into DB Table
app/views.py
def savePublisher(request):
name = request.POST.get("name")
Publisher(name=name).save()
return render(request,"index.html")
def saveArticle(request):
name = request.POST.get("name")
publisher = request.POST.getlist("pub")
ar = Article(name=name)
ar.save()
ar.pub.set(publisher)
To View all Articles with Publisher's
templates/article.html
<table align="center" border="2">
<tr><th>NO</th><th>NAME</th><th>PUBLISHER'S</th></tr>
{% for x in data %}
<tr>
<th>{{ x.idno }}</th>
<th>{{ x.name }}</th>
<th>
{% for y in x.pub.all %}
{{ y }}<br>
{% endfor %}
</th>
</tr>
{% endfor %}
</table>
Many-to-one relationship
To define a many-to-one relationship, use ForeignKey:
app/models.py
from django.db import models
class BiryaniTypes(models.Model):
no = models.AutoField(primary_key=True)
type = models.CharField(max_length=30)
class Biryanis(models.Model):
no = models.AutoField(primary_key=True)
type_of_biryani =
models.ForeignKey(BiryaniTypes,on_delete=models.CASCADE)
name = models.CharField(max_length=30)