Open In App

Django Dynamic Model Fields

Last Updated : 12 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In web development, Django is a framework that helps to build awesome websites. One of the main features of Django is dynamic model fields so we will discuss what we mean by dynamic model fields and how to use them in Django. In this article, we will read about the dynamic model fields in Django.

What are Django Dynamic Model Fields?

Dynamic Model fields in Django let you create a model that can change or grow over time when you use dynamic model fields. Dynamic model fields are like a magic box; you can put anything you want and the box adjusts to fit all. For example, you are making a digital library where people can add their types of books. Some might want to add cookbooks, others might add novels and some might even comics so how can you handle all these different types without making a mess? that’s all we can handle using Django’s dynamic model field.

Django Dynamic Model Fields

Below are the examples of Django dynamic model fields in Python:

Starting the Project Folder

To start the project use this command

django-admin startproject demo
cd demo

To start the app use this command

python manage.py startapp firstt

Now add this app to the ‘settings.py’

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "firstt",
]

File Structure

Screenshot-(102)

Example 1: Generic Relations in Dynamic Model Fields

Generic Relations:

This is like having a magic key that can open any door. With Django’s GenericForiegnKey, you can connect one thing to another thing without knowing what those things are in advance.

Django’s GenericForiegnKey allows a model to reference any other model instance through the foreign key.

firstt/models.py : To understand the dynamic field models using Generic Relations. I take examples of comments on videos and photos. So I have created a model of photos, videos and comments. In the below code, comment models have a generic relation with photos and videos.

Python3
# models.py
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models


class Comment(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    text = models.TextField()


class Photo(models.Model):
    caption = models.CharField(max_length=100)


class Video(models.Model):
    title = models.CharField(max_length=100)

firstt/views.py : After creating a model I have created a view for testing generic relations. In views, I have created function generic function and in generic function, views I have added one photo and video then added a comment photo and video after this, I filtered based on content and showed the comments for photos and videos.

Python3
# views.py
from django.shortcuts import render
from .models import Photo, Video, Comment, ContentType
from django.http import HttpResponse
# Create your views here.


def generic_function(request):
    photo = Photo.objects.create(caption="Beautiful sunset")
    video = Video.objects.create(title="Funny cat video")

    comment1 = Comment.objects.create(
        content_object=photo, text="Amazing photo!")
    comment2 = Comment.objects.create(
        content_object=video, text="Hilarious video!")

    photo_comments = Comment.objects.filter(
        content_type=ContentType.objects.get_for_model(photo), object_id=photo.id)
    video_comments = Comment.objects.filter(
        content_type=ContentType.objects.get_for_model(video), object_id=video.id)

    print("Comments on Photo:")
    for comment in photo_comments:
        print(comment.text)

    print("\nComments on Video:")
    for comment in video_comments:
        print(comment.text)
    return HttpResponse("Generic Function")

firstt/urls.py : After adding the URL of the generic function in urls.py

Python3
# urls.py
from django.urls import path
from .views import generic_function

urlpatterns = [
    path('generic/', generic_function, name='generic-url'),
]

After running of local server(http://127.0.0.1:8000/). I have hit this URL (http://127.0.0.1:8000/generic/).

Example 2: JSON Fields (Dynamic Model Fields)

JSONField allows storing JSON data in native JSON format in the database. This field type is particularly useful when you dealing with semi-structure or unstructure data. It is like a big bag where you can all sorts of stuff without worrying about organising it.

Let’s say you’re developing a platform where users can create custom forms, each with different fields based on their needs. Instead of defining fixed fields for each form, you can use a JSON field to store the form data flexibly. To create this platform we create the first model ‘CustomForm’.

firstt/models.py : In the below code, I have created the model CustomForm. In CustomForm Field add name field and form_data field. form_data field is JSONField so in this field, you can add different fields of different users. For testing these fields I have created a view.

Python3
# models.py
from django.db import models

class CustomForm(models.Model):
    name = models.CharField(max_length=100)
    form_data = models.JSONField()

firstt/views.py : This code dynamically generates a custom form using the provided form_data, creates a CustomForm object with this data, and then returns the form data as an HTTP response

Python3
# views.py
def Json_Field(request):
    # Create a custom form
    form_data = {
        "fields": [
            {"name": "name", "type": "text", "label": "Your Name", "required": True},
            {"name": "email", "type": "email",
                "label": "Your Email", "required": True},
            {"name": "message", "type": "textarea",
                "label": "Your Message", "required": False}
        ]
    }
    custom_form = CustomForm.objects.create(
        name="Contact Form", form_data=form_data)

    # Retrieve the custom form data
    print("Custom Form Data:")
    print(custom_form.form_data)
    return HttpResponse(f"{custom_form.form_data}")

firstt/urls.py : In this example, I have added data from three persons from different fields.
Add Json_Field views in URLs.

Python3
#urls.py

from django.urls import path
from .views import *

urlpatterns = [
    path('generic/', generic_function, name='generic-url'),
    path('json/', Json_Field, name='json-url'),
]

admin.py : I have register all models in admin portal.

Python3
# admin.py
from django.contrib import admin
from .models import Comment, Photo, Video, CustomForm

# Register your models here.
admin.site.register(Comment)
admin.site.register(Photo)
admin.site.register(Video)
admin.site.register(CustomForm)

After running of local server(http://127.0.0.1:8000/). I have hit this URL (http://127.0.0.1:8000/json/). In above all example code we need to make migration on code for those follow the below steps, and run in terminal below command.

Deployment of the Project

Run these commands to apply the migrations:

python3 manage.py makemigrations
python3 manage.py migrate

Run the server with the help of following command:

python3 manage.py runserver

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads