My First Django Website #3

This next chapter of the tutorial goes over models. Models are usually defined in an application’s models.py file. They are implemented as subclasses of django.db.models.Model, and can include fields, methods, and metadata.

A model can have an arbitrary number of fields, of any type — each one represents a column of data that we want to store in one of our database tables. Each database record (row) will consist of one of each field value.

You can declare model-level metadata for your Model by declaring class Meta

A model can also have methods. Minimally, in every model, you should define the standard Python class method __str__() to return a human-readable string for each object. This string is used to represent individual records in the administration site (and anywhere else you need to refer to a model instance). Often this will return a title or name field from the model.

def __str__(self):
return self.field_name

Another common method to include in Django models is get_absolute_url(), which returns a URL for displaying individual model records on the website (if you define this method then Django will automatically add a "View on Site" button to the model's record editing screens in the Admin site). A typical pattern for get_absolute_url() is shown below.

def get_absolute_url(self):
"""Returns the url to access a particular instance of the model."""
return reverse('model-detail-view', args=[str(self.id)])

Once you’ve defined your model classes you can use them to create, update, or delete records, and run queries to get all records or particular subsets of records.

Creating Model Instances:

# Create a new record using the model's constructor.
record = MyModelName(my_field_name="Instance #1")

# Save the object into the database.
record.save()

Searching:

all_books = Book.objects.all()wild_books = Book.objects.filter(title__contains='wild')
number_wild_books = wild_books.count()

Creating Models:

class Author(models.Model):
"""Model representing an author."""
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=True, blank=True)
date_of_death = models.DateField('Died', null=True, blank=True)

class Meta:
ordering = ['last_name', 'first_name']

def get_absolute_url(self):
"""Returns the url to access a particular author instance."""
return reverse('author-detail', args=[str(self.id)])

def __str__(self):
"""String for representing the Model object."""
return f'{self.last_name}, {self.first_name}'