What is the process that you follow to create model in Django? - 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

Related

django models hierarchy question: related attributes of a ManyToManyField

As a fresh coder, I seriously have problems to build my models relations.
Please check these two cases, How can I set current_reading_pages on my Scenario2?
from django.db import models
# Scenario1: Users can record their reading progress of a book.
class Book(models.Model):
name = models.CharField(max_length=128)
class User(models.Model):
current_reading_book = models.ForeignKey('Book', on_delete=models.CASCADE)
current_reading_page = models.IntegerField()
Result1: No problems about database, but Users can records their progress of only one book.
Other scenario, which I want to build:
from django.db import models
# Scenario2: Users can record their reading progress of multiple books.
class Book(models.Model):
name = models.CharField(max_length=128)
class User(models.Model):
current_reading_books = models.ManyToManyField('Book')
# current_reading_pages = ???
I want to save all progress of current books, for example,
User A is reading 3 books, book1 till page 100, book2 till page 10, book3 till page 0.
And I found 'through' parameter in django ManyToManyField,
My codes become like below but it does not work as I expected.
from django.db import models
# Scenario3: Using through parameter in ManyToManyField
class Book(models.Model):
name = models.CharField(max_length=128)
class User(models.Model):
current_reading_books = models.ManyToManyField('Book', through='ReadingBook')
class ReadingBook(models.Model):
book = models.ForeignKey('Book', on_delete=models.CASCADE)
current_reading_page = models.IntegerField()
ERRORS:
test_model.ReadingBook: (fields.E336) The model is used as an intermediate model by 'test_model.User.current_reading_books', but it does not have a foreign key to 'User' or 'Book'.
I think, that first scenario is easy to realize.
just add user attribute into the custom class UserBook
for example
class UserBooks(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
current_page = models.IntegerField(default=1)
if user wanna check his progress, in views.py you can just filter by books = UserBooks.objects.filter(user=request.user)

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.

Filtering Django query filtering

I'm doing some querying currently and I was wondering if I would be able to query something from these 3 models where the return would give me all the projects the users are working on. I know about the basic filtering however thats not really enough in this case, how would one go about querying through 2 foreign keys.
class User(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField()
class ProjectUser(models.Model):
project = models.ForeignKey("Project", on_delete=models.CASCADE)
user = models.ForeignKey("User", on_delete=models.CASCADE)
is_lead = models.BooleanField(default=False)
class Meta:
unique_together = (("project", "user"),)
class Project(models.Model):
name = models.CharField(max_length=255)
client = models.CharField(max_length=255)
complete = models.BooleanField(default=False)
You can obtain the Projects a user is working on with:
Project.objects.filter(
projectuser__user=user
)
The double underscores are used to look "through" relations. Furthermore the default related_query_name=… parameter [Django-doc] is, if not specified, the name of the model in lowercase.

Django model to record transactions from two different apps of a Bookstore website

I am new to Django and i'd like to build a bookstore. The site will sell 2 types of products (Books and Individual question solutions) and i have split those into 2 different django apps. How can i handle the final individual purchases. Is there a way to for example have 1 'Purchase' model that will recieve either Books or Solutions and save transaction into database upon completion of purchase ?
I want this Purchase model to have title, date of purchase, customer info (name and email).
Sure, you are very flexibel when using Django.Models. Since one/many-to-many fields can "link information" behind the scenes, there are close to no limits.
You may start with this model structure in your app:
from django.db import models
# Basic Books Model
class BooksPurchase(models.Model):
books_title = models.CharField(max_length=150, blank=False)
books_purchase_date = models.DateTimeField(blank=False)
books_customer_name = models.CharField(max_length=150, blank=False)
books_customer_email = models.CharField(max_length=150, blank=False)
class Meta:
db_table = 'books_purchase'
# Basic Solutions Model
class Solutions(models.Model):
solutions_title = models.CharField(max_length=150, blank=False)
[...]
class Meta:
db_table = 'solutions_information'
# Basic User Model
class Customers(models.Model):
customer_name = models.CharField(max_length=150, blank=False)
customer_mail = models.CharField(max_length=150, blank=False)
[...]
class Meta:
db_table = 'customer_data'
Note that you can use any Model within any file of your Django project by just importing it:
from app.models import model_name
Also don't forget to run makemigrations and migrate to push the model to the DB.

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)