[Django]-Does Django allow one to define different set of fields for each document in MongoDB?

4πŸ‘

βœ…

The Alternative

I like using django-mongoengine as it makes things clearer when dealing with MongoDB models.

For example, you can create structured Documents that are going to be transformed into models or EmbeddedDocument`s that are structured documents to be used in an already existed model.

from django_mongoengine import Document, EmbeddedDocument, fields

class Comment(EmbeddedDocument):
    created_at = fields.DateTimeField(
        default=datetime.datetime.now, editable=False,
    )
    author = fields.StringField(verbose_name="Name", max_length=255)
    email  = fields.EmailField(verbose_name="Email")
    body = fields.StringField(verbose_name="Comment")

class Post(Document):
    created_at = fields.DateTimeField(
        default=datetime.datetime.now, editable=False,
    )
    title = fields.StringField(max_length=255)
    slug = fields.StringField(max_length=255, primary_key=True)
    comments = fields.ListField(
        fields.EmbeddedDocumentField('Comment'), blank=True,
    )

The Answer

So for your case what you need to use is Dynamic document schemas that work in the same way as Document but any data/attributes set to them will also be saved.

class Page(DynamicDocument):
    title = StringField(max_length=200, required=True)

# Create a new page and add tags
>>> page = Page(title='Using MongoEngine')
>>> page.tags = ['mongodb', 'mongoengine']
>>> page.save()

>>> Page.objects(tags='mongoengine').count()
>>> 1
πŸ‘€iamjazzar

0πŸ‘

I struggled this problem in user profile page. This is my solution.

model.py

from django.contrib.auth.models import User
from django.db import models
from django.core.validators import RegexValidator

# Create your models here.
class Profile(models.Model): 


    
    user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,related_name="user_profile")
    fullname = models.CharField(max_length=100,verbose_name="full name")     
    about = models.CharField(max_length=300,blank=True,null=True)
    hobies = models.CharField(max_length=200,blank=True)
    recent_aktivity = models.CharField(max_length=150,verbose_name="recent activity",null=True)
    photo = models.ImageField(blank=True,null=True,upload_to="images/")
    recent_badges = models.CharField(max_length=100,verbose_name="recent badges",null=True)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True,null=True,verbose_name="phone number") 
    website_url = models.URLField(blank=True,null=True,verbose_name="company website")
    projects =models.CharField(max_length=200,blank=True,null=True)
    bio = models.CharField(max_length=300,blank=True,null=True)
    
    
    
    def __str__(self):
        return f'{self.user.username}-ProfileModel'

signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from .models import Profile

@receiver(post_save,sender=User)
def update_user_profile(sender,instance,created,**kwargs):
    if created:
        profile = Profile.objects.create(user =instance)

app.py

from django.apps import AppConfig


class ProfileConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'Profile'

    def ready(self):
        import Profile.signals

forms.py

from django import forms
from.models import Profile



class ProfileForm(forms.ModelForm):   
        
    
      class Meta:
          model = Profile
          fields = '__all__'
          exclude = ['user']

views.py

 from django.contrib import messages
    from django.contrib.auth.decorators import login_required
    from django.http import HttpResponseRedirect
    from django.urls.base import reverse
    from .forms import ProfileForm
    from .models import Profile
    from django.shortcuts import redirect, render,get_object_or_404
    from django.contrib.auth import update_session_auth_hash
    from django.contrib.auth.forms import PasswordChangeForm
    
    login_required(login_url="user:login")
    def dashboard(request):
        return render(request,"dashboard.html")
    
    
    @login_required(login_url="user:login")
    def get_profile(request):    
        
        profile = get_object_or_404(Profile,user=request.user)
        
    return render(request,"profile.html",{"profile":profile})
πŸ‘€user12038667

Leave a comment