Django Model
Django Model
A template is a class representing a table or collection in our DB and where each class attribute is a table or collection area. In the app / models.py, models are described (in our example: myapp / models.py)
Model is defined in Models.py file. This file can contain multiple models.
Creating a Model
from django.db import models class Django(models.Model): website = models.CharField(max_length = 20) mail = models.CharField(max_length = 10) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Meta: db_table = “Django"
The first_name and last_name fields are specified as class attributes and each attribute maps to a database column.
The model will create a table look like this.
CREATE TABLE appname_employee ( "id" INT NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL );
Django Model Field.
Field Name | Class | Particular |
AutoField | Class field(option) | It is an integer field and it increment automatically. |
BigAutoFeild | Class BigAutofield(option) | It is same as like Autofield. It is 64bit integer, that guarantees to fit a number from 1 to 9223372036854775807 |
BigIntegerfield | Class BigIntegerField | It is also 64bit integer, It guarantees to fit number from -9223372036854775808 to 9223372036854775807 |
BinaryField | Class BinaryField | It is used to store binary raw data. |
CharField | Class DateField(auto_now=False,auto_now_add=false) | It is used to represent datetime.date instance in python language. |
BooleanField | Class BooleanField | A domain true / false. A CheckboxInput is the default form widget for this area. |
DateTimeField | Class DateTimeField(auto_now=False,auto_now_add=False) | It is used for date and time, a datetime.datetime instance is defined in Python. |
DecimalField | Class DecimalField(max_digits=None, decimal_places=None) | It is a decimal number of fixed-precision, represented by a Decimal example in Python. |
DurationField | Class DurationField(**option) | This field is used for storing periods of time |
EmailField | Class EmailField(max_length=254) | It is a CharField that searches for a valid email address to be the value. |
FileField | Class FileField(upload_to=None,max_length=100) | It is file-upload field |
FloatField | Class FloatField(**option) | It is a number of floating-points defined by a float instance in Python. |
ImageField | Class ImageField(upload_to=None,height_field=None,width_field=None,max_length=100) | It inherits all FileField attributes and methods, but also validates that a valid image is the uploaded object. |
IntegerField | Class IntegerField(**option) | It's a domain of integer. In all Django-supported databases, values from -2147483648 to 2147483647 are free. |
NullBooleanField | Class NullBooleanField(option) | It is like a BooleanField, but only allows Null as one of the option. |
PositiveIntegerField | Class PositiveIntegerField(option) | Like an IntegerField, but it must either be positive or zero (0). Values between 0 and 2147483647 are safe in all Django-based databases. |
TextField | Class TextField(otion) | It is wide area for text. |
TimeField | class TimeField(auto_now=False,auto_now_add=False) | A time, defined by a datetime.time example in Python. |
Manuplating Data (CRUD)
Let's create a "crudops" view to see how we can perform CRUD operations on models. Our myapplication/views.py will look this while performing CRUD operation.
myapplication/views.py
from myapp.models import Dreamreal from django.http import HttpResponse def crudops(request): #Creating an entry dreamreal = Dreamreal( website = "www.polo.com", mail = "[email protected]", name = "=sum", phonenumber = "123456789" ) dreamreal.save() #Read ALL entries objects = Dreamreal.objects.all() res ='Printing all Dreamreal entries in the DB : <br>' for elt in objects: res += elt.name+"<br>" #Read a specific entry: sorex = Dreamreal.objects.get(name = "sorex") res += 'Printing One entry <br>' res += sum.name #Delete an entry res += '<br> Deleting an entry <br>' sorex.delete() #Update dreamreal = Dreamreal( website = "www.sum.com", mail = "[email protected]", name = "sum", phonenumber = "123456789" ) dreamreal.save() res += 'Updating entry<br>' dreamreal = Dreamreal.objects.get(name = 'sum') dreamreal.name = 'thierry' dreamreal.save() return HttpResponse(res)
Other Manuplation Data
Let's discuss other design and manipulation operations that we can do. Note that the CRUD operations were done on our model's instances, now we're going to work directly with the model's class.
Creating ‘datamanuplation’ view in myapplication/views.py
from myapp.models import Dreamreal from django.http import HttpResponse def datamanipulation(request): res = ' ' #Filtering data: qs = Dreamreal.objects.filter(name = "paul") res += "Found : %s results<br>"%len(qs) #Ordering results qs = Dreamreal.objects.order_by("phone") for elt in qs: res += elt.name + '<br>' return HttpResponse(res)
Linking Models
It is used in 3 ways to link:
In first case we will show one-to-many relationships. As you can see in the below example. Most company can have multiple websites online. Use django.db.models.ForeignKey to describe the relationship
myapplication/model.py
from django.db import models class Dreamreal(models.Model) websitename = models.CharField(max_length = 50) mailid = models.CharField(max_length = 60) : firstname = models.CharField(max_length = 60) phonenumber = models.IntegerField() online = models.ForeignKey('Online', default = 1) class Meta: db_table = "dreamreal" class Online(models.Model): domain = models.CharField(max_length = 20) class Meta: db_table = "online"
Let's check how all of this is working via manage.py shell –
Creating some companies (Dreamreal entries) for testing in our Django shell –
python manage.py shell >>> from myapplication.models import Dreamreal, Online >>> dr1 = Dreamreal() >>> dr1.website = 'company1.com' >>> dr1.name = 'company1' >>> dr1.mail = 'dream@company1' >>> dr1.phonenumber = '12385945' >>> dr1.save() >>> dr2 = Dreamreal() >>> dr1.website = 'company2.com' >>> dr2.website = 'company2.com' >>> dr2.name = 'company2' >>> dr2.mail = 'dream@company2' >>> dr2.phonenumber = '1236989' >>> dr2.save()
Some Hosted Domain
>>> on1 = Online() >>> on1.company = dr1 >>> on1.domain = "site1.com" >>> on2 = Online() >>> on2.company = dr1 >>> on2.domain = "site2.com" >>> on3 = Online() >>> on3.domain = "site3.com" >>> dr2 = Dreamreal.objects.all()[2] >>> on3.company = dr2 >>> on1.save() >>> on2.save() >>> on3.save()
It is easy to access the hosting company's attribute from an online domain
>>> on1.company.name
And if we want to learn all the online territory of a client in Dreamreal, we're going to use this code
>>> dr1.online_set.all()
Note that all the manipulative methods that we've seen before (filter, all, exclude, order by ...) is to get a QuerySet.
You can also access the related template attributes for filtering operations, let's say you want to get all online domains where the name of Dreamreal includes ' business '
>>> Online.objects.filter(company__name__contains = 'company'
For SQL DB, this kind of query is only supported. It will not work for non-relational DB where there are no joins and there are two ' .'
But this is not the only way models can be connected, you also have OneToOneField, a connection that ensures the unique relationship between two objects. In our example above, if we use the OneToOneField, it means only one Online entry is possible for each Dreamreal entry and the other way.
And the last one, the tables relationship ManyToManyField (n-n). Note that these are relevant to DB based on SQL.