How to create relative entry in mongoldb using Django? - django

I have following Person document model.
from djongo import models
from django.contrib.postgres.fields import ArrayField
class Person(models.Model):
id = models.ObjectIdField()
name = models.CharField(max_length=255)
city = models.CharField(max_length=255)
status = models.CharField(max_length=20)
phone_number = models.CharField(max_length=20)
objects = models.DjongoManager()
And the following Comment model
class Comment:
id = models.OneToOneField(
Person,
on_delete=models.CASCADE,
primary_key=True,
)
comments = ArrayField(models.CharField())
objects = models.DjongoManager()
When I create a document in Person object, I want mongo automatically create a document in Comment model with the same id but empty comments. I thought declaring OneToOneField filed will do it, but it didn't. What should I do?

Related

django howto use select_related not using local id key

i have made two models where i would like to get them joined on the two name keys.
models.py
class MODELa (models.Model):
......
nameXX = models.CharField(_("name"), max_length=255, primary_key=True)
class MODELb (models.Model):
......
nameYY = models.CharField(_("nameYY"), max_length=255)
FKxx = models.ForeignKey(to=MODELa, on_delete=models.CASCADE, null=True)
views.py
rows = MODELb.objects.all().select_related('FKxx')
using debug toolbar, i can see the join is using the id field
LEFT OUTER JOIN "MODELa"
ON ("MODELb"."FKxx_id" = "MODELa"."nameXX")
How do i set it use the local key nameYY?

Django error with models (ManyToManyField)

I was building my app using django but I got this error in the models.py file:
creator = models.ManyToManyField(Teacher, on_delete=models.CASCADE)
NameError: name 'Teacher' is not defined
This is my current code in models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class School(models.Model):
nombre = models.CharField(max_length=355)
profesoras = models.ManyToManyField(Teacher)
class Teacher(models.Model):
user = models.ForeignKey(User, related_name="teacherClass", blank=False)
school = models.ManyToManyField(School, blank=True)
class Post(models.Model):
creator = models.ManyToManyField(Teacher, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
text = models.TextField(max_length=2000)
Do you know how can I solve this error?
The issue here is that you are trying to reference a model that has not been created yet. The Django docs state what to do in such a case.
If you need to create a relationship on a model that has not yet been
defined, you can use the name of the model, rather than the model
object itself:
class Car(models.Model):
manufacturer = models.ForeignKey(
'Manufacturer',
on_delete=models.CASCADE,
)
# ...
class Manufacturer(models.Model):
# ...
pass
So for your case, you would just change your model relationships to strings.
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class School(models.Model):
nombre = models.CharField(max_length=355)
profesoras = models.ManyToManyField("Teacher") # Make this a string because it has not been defined yet
class Teacher(models.Model):
user = models.ForeignKey(User, related_name="teacherClass", blank=False)
school = models.ManyToManyField(School, blank=True)
class Post(models.Model):
creator = models.ManyToManyField("Teacher", on_delete=models.CASCADE) # Same with this one.
title = models.CharField(max_length=255)
text = models.TextField(max_length=2000)
The django docs are always really useful and have a lot of good information.
The error is just fine because you are using it before declaring it and also your relationships are a little messy. You can say that you can have as many schools as you wish in this app and each professor teaches in many schools so it can be something like this by using many to many relation:
class School(models.Model):
name = models.CharField(max_length=355)
class Teacher(models.Model):
user = models.ForeignKey(User, related_name="teacherClass", blank=False, on_delete=models.CASCADE)
school = models.ManyToManyField(School, blank=True)
class Post(models.Model):
creator = models.ManyToManyField(Teacher)
title = models.CharField(max_length=255)
text = models.TextField(max_length=2000)
I suggest you that study a little bit about relations in databases so you won't have any similar problem in future.

Django ORM - model referencing another models ManyToMany field

I'm currently trying to setup some database models in djangos ORM. however im unable to figure out how i'm supposed to reference another models many-to-many- field.
Project model
class Project(models.Model):
projectName = models.CharField(max_length=200)
users = models.ManyToManyField(get_user_model())
projectOwner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='projectowner', default=1)
The users = models.manytomanyfield(get_user_mode()) works fine
and generates the correct relation in the database.
now i want to add a new model that adds a many to many relation between rights and project_user
so what the end result tables are supposed to look like:
project:
projectname - string
projectowner - id of referenced user
user: django orm auth user model
rights:
name
description
etc
project_user:
id
project_id
user_id
rights_projectuser:
id
rights_id
project_user_id
now that last one (rights_projectuser) is what i dont know how to make.
You need to turn "project_user" into a through model that you can then add the many to many relationship to.
class Project(models.Model):
projectName = models.CharField(max_length=200)
users = models.ManyToManyField(get_user_model(), through='ProjectUser')
class ProjectUser(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
rights = models.ManyToManyField(Right)
i now get the following problem when running this code:
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Project(models.Model):
projectName = models.CharField(max_length=200)
users = models.ManyToManyField(get_user_model(), through='ProjectUser')
projectOwner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='projectowner', default=1)
class Right(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=1000)
class ProjectUser(models.Model):
user_id = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
project_id = models.ForeignKey(Project, on_delete=models.CASCADE)
rights = models.ManyToManyField(Right)
ValueError: Cannot alter field wspingpong.Project.users into wspingpong.Project.users - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)

What is the relation of these 3 models: user, birthday, label?

I'm creating a birthday calendar app. It will have the following models:
- Django's user model
- Birthday
- Label (i.e. friends, family)
I'm not sure how to model the Label class. The user should have the ability to create a new Label object which can then be used when creating a Birthday object.
The user should also be able to filter Birthday's based on the Label.
How would you model these relationships in a db?
from django.conf import settings
from django.db import models
from django.utils import timezone
class Birthday(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=25)
day = models.DateField()
class Label(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
tag = models.CharField(max_length=25)
class Label(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
tag = models.CharField(max_length=25)
class Birthday(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=25)
day = models.DateField()
label = models.ForeignKey(Label, on_delete=models.CASCADE)
Use Label as the Foreignkey of Birthday. So you will know which birthday is related to which Label.
You can then filter out Birthday based on label like this.
Birthday.objects.filter(label__id=1)
As I can understand, you can add Label as ManyToMany Field in Birthday Model. In that way, you can assign this label/labels to Birthday. You can have multiple label to a birthday, and one label can have multiple birthdays. So it will be like this:
class Birthday(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=25)
day = models.DateField()
labels = models.ManyToManyField(Label)
Usage:
birthday = Birthday.objects.create(...)
label = Label.objects.create(...)
b.labels.add(label)
Birthday.objects.filter(labels=label)

What is the process that you follow to create model in Django?

What is the process that you follow to create model in Django? Thanks.
The most important part of a model – and the only required part of a model – is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete.
Models.py
from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
You can start here Documentation
See also Django Girls Models