0% found this document useful (0 votes)
52 views4 pages

Many-To-Many Relationships: To Define A Many-To-Many Relationship, Use

The document discusses many-to-many and many-to-one relationships in Django models. It provides code examples for defining these relationships using ManyToManyField and ForeignKey, and retrieving related objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views4 pages

Many-To-Many Relationships: To Define A Many-To-Many Relationship, Use

The document discusses many-to-many and many-to-one relationships in Django models. It provides code examples for defining these relationships using ManyToManyField and ForeignKey, and retrieving related objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

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)

You might also like