To create a table follow these stems:
- Create the model in the model.py folder in its app folder
- Make migration files python manage.py makemigrations this will create the migration files
- Run the migration python manage.py migrat and that will create the tables
Notes:
-
Adding from django.db import models is a must
-
To use a foreign key you need to import the model from realtors.models import Realtor
-
on_delete=models.DO_NOTHING tells what we want to happen if the record of the foreign key deleted
-
To create a field of type date format you need to import datetime model from datetime import datetime
-
To specify a folder for uploads use upload_to=’photos/%y/%m/%d’ you need to run pip install Pillow
Some parameters to use:
-
(max_length=200)
-
(blank=True) can be null
-
(max_digits=2, decimal_places=1) use with decimal
-
(default=0) set a default value
Here are some models examples:
Listings Model: listings/model.py
class Listing(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=200)
address = models.CharField(max_length=200)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
zapcode = models.CharField(max_length=20)
description = models.TextField(blank=True)
price = models.IntegerField()
bedrooms = models.IntegerField()
bathrooms = models.DecimalField(max_digits=2, decimal_places=1)
garage = models.IntegerField(default=0)
sqft = models.IntegerField()
lot_size = models.DecimalField(max_digits=5, decimal_places=1)
photo_main = models.ImageField(upload_to=’photos/%y/%m/%d’, blank=True)
photo_1 = models.ImageField(upload_to=’photos/%y/%m/%d’, blank=True)
photo_2 = models.ImageField(upload_to=’photos/%y/%m/%d’, blank=True)
photo_3 = models.ImageField(upload_to=’photos/%y/%m/%d’, blank=True)
photo_4 = models.ImageField(upload_to=’photos/%y/%m/%d’, blank=True)
photo_5 = models.ImageField(upload_to=’photos/%y/%m/%d’, blank=True)
photo_6 = models.ImageField(upload_to=’photos/%y/%m/%d’, blank=True)
is_published = models.BooleanField(default= True)
list_date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
Relator Model: realtors/model.py
from django.db import models
from datetime import datetime
class Realtor(models.Model):
name = models.CharField(max_length=200)
photo = models.ImageField(upload_to='photos/%y/%m/%d', blank=True)
description = models.TextField(blank=True)
phone = models.CharField(max_length=20)
email = models.CharField(max_length=50)
is_mvp = models.BooleanField(default=False)
hire_date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.name