Introduction to model.py file
In Django, models.py is a Python module that contains the definition of the data models for your application. Each model maps to a database table, and the fields of the model correspond to the columns of the table.
A model is a class that represents a single table in our Database. Django Model is a subclass of django.db.models.Model and each field of the model class represents a database field (column).
Models are defined in a models.py file (example: myapp/models.py)
#models.py
from django.db import models
import uuid
from django.utils.safestring import mark_safe
def uuid_generate():
return uuid.uuid4().hex
class User(models.Model):
# Fields
CHOICES = (
('Male', 'Male'),
('Female', 'Female'),
)
ref_no=models.AutoField(primary_key=True)
uuid = models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False)
id = models.CharField(
max_length=32, default=uuid_generate, unique=True, primary_key=True, editable=False)
first_name = models.CharField(max_length=255, )
last_name = models.CharField(max_length=255, )
product=models.IntegerField()
quantity=models.IntegerField()
amount=models.DecimalField(decimal_places=2,max_digits=10)
myfile=models.FileField(upload_to="file")
picture=models.BinaryField()
email = models.EmailField(max_length=255,unique=True,verbose_name="Email Address")
description = models.TextField()
gender = models.CharField(max_length=255, choices=CHOICES, blank=True, null=True)
profile = models.ImageField(upload_to="profile", null=True,default="nepal.png")
#default image must be in media/ directory
date_joined = models.DateTimeField(('date joined'), auto_now_add=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=True)
created_by = models.ForeignKey(
'self', on_delete=models.PROTECT, related_name="+", db_column="created_by", null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = "USER"
ordering = ['name']
db_table = "user"
unique_together = ("", "")
def get_absolute_url(self):
return reverse('user-view', args=[str(self.id)])
def __str__(self):
return '%s - %s' % (self.id, self.name)
def save(self, *args, **kwargs):
if self.customer_name == None:
self.customer_name = datetime.datetime.now()
super(Customer, self).save(*args, **kwargs)
if self._state.adding:
try:
check_invoice = Invoice.objects.first()
except Exception:
check_invoice = None
if check_invoice:
last_invoice = Invoice.objects.order_by("invoiceNumber").last()
last_num = last_invoice.invoiceNumber
else:
last_num = 1000
num = last_num + 1
self.invoiceNumber = num
super(Invoice, self).save(*args, **kwargs)
@property
def get_full_name(self):
return f'{self.first_name or ""} {self.last_name or ""}'
@property
def price(self):
return (self.product.price)
@property
def amount(self):
return (self.product.price*self.quantity)
#to show image in admin panel list
def image_tag(self):
return mark_safe('<img src="{}" width="50' height="50"/>'.format(self.profile.url))
image_tag.short_description="Image"
#then in admin fille list_display you can mention "image_tag"
def color_by(self):
return mark_safe('<div style="width:50px;height=50px;background-color:%s"></div>',%(self.color_code)
Once you define models, you need to register your app in INSTALLED_APPS list so that Django know that you are going to use those models.
#settings.py
INSTALLED_APPS = [
#…
"Blog",
#….
]
Onces you add you app in INSTALLED_APPS you need to run two commands makemigrations and migrate.
makemigrations basically generates the SQL commands for preinstalled apps.
Python manage.py makemigrations
migrate creates the table in the database
Python manage.py migrate
Additional, if you want to save the image in specific path then you can custom it like
#models.py
def path_and_rename(instance,filename):
upload_to='Images/'
ext=filename.split(".")[-1] #to get extension
if instance.user.username:
filename="user_profile_picture/{}.{}".format(instance.user.username,ext)
if os.path.exists(filename):
new_name=str(instance.user.username)+str("1")
filename="user_profile_picture/{}.{}".format(new_name,ext)
return os.path.join(upload_to,filename)
#then change, imagefield attribute as
photo=models.ImageField(upload_to=path_and_rename)
In this tutorial we will learn about the additional concept of model in django
Django Model Relationship
Django provides three ways to define database relationships.
- One to One Relationship
- One to Many Relationship
- Many to Many Relationships