Relationships and Forms in Django
Relationships and Forms in Django
Relationships in Django
Django has a number of built-in relationships that you can use to connect your models to each other. The most common relationships are:
- One-to-many
- Many-to-many
- One-to-one
One-to-many
One-to-many relationships are used when you have a model that has a foreign key to another model. In a One-to-Many relationship, each instance of the parent model can be associated with multiple instances of the child model. For example, a Chai variety can have multiple reviews.
In the existing chai
app, open models.py
and add the following code:
This code creates a new model called ChaiReview
that has a foreign key to the ChaiVariety
model. The user
field is a foreign key to the User
model, and the rating
and comment
fields are integers and text fields respectively.
Many-to-many
Many-to-many relationships are used when you have a model that has a many-to-many relationship with another model. In a Many-to-Many relationship, each instance of one model can be associated with multiple instances of another model, and vice versa. For example, a Chai variety can be featured in multiple stores, and each store can feature multiple chai varieties.
In the existing chai
app, open models.py
and add the following code:
One-to-one
One-to-one relationships are used when you have a model that has a one-to-one relationship with another model. In a One-to-One relationship, each instance of one model is associated with one and only one instance of another model. For example, each Chai variety can have a unique certificate.
In the existing chai
app, open models.py
and add the following code:
Update the admin
In the existing chai
app, open admin.py
and add the following code:
Adding a form on frontend
In the existing chai
app, create a new file called forms.py
in the chai
app directory. In this file, add the following code:
Handle the view for the form
In the existing chai
app, open views.py
and add the following code:
Add the template
In the existing chai
app, create a new file called chai_stores.html
in the chai
app directory. In this file, add the following code:
Update the urls
In the urls.py
file, add the following code to the urlpatterns
list:
Run the server
In the terminal, navigate to the chai
directory and run the following command:
That’s it! You have successfully created a form that allows users to search for stores that have a specific chai variety. You can now add more functionality to the form and the view to make it more useful.
Conclusion
In this section, you learned how to create a form that allows users to search for stores that have a specific chai variety. We have also discussed about the different types of relationships in Django and how to use them in your models and views. Hope this was helpful! Stay tuned for the next part of the tutorial where we will learn how to create a form that allows users to add a new chai variety to the database.