Model elements

Class Meta

Class Meta is used to provide metadata about the model. It is used to define various options and behaviors for the model.

Some of the common options that can be defined in the class Meta are:




get_absolute_url

def get_absolute_url(self):
    return reverse('homepage') # once we have a designated page to list all species, we will update this method

When this method is defined in a model, it allows Django to generate URLs for individual instances of that model. This can be useful, for example, when you want to create a link to a specific page or detail view for an object. For example:

from django.urls import reverse
  from django.db import models
  class MyModel(models.Model):
      name = models.CharField(max_length=50)
      def get_absolute_url(self):
          return reverse('myapp:detail', args=[str(self.id)])

In this example, the get_absolute_url method returns a URL that would point to a view named detail in the myapp application, passing the id of the object as an argument. This would generate a URL like /myapp/1/, where 1 is the ID of the object.

By defining this method, you can then use the get_absolute_url method to generate URLs to individual instances of the model throughout your application. For example, in a template you might use the url template tag to create a link to the detail view for a particular object: myobject.get_absolute_url




__str__

def __str__(self):
    return f"{self.species_name}"

In Django models, the __str__() method is used to define the string representation of an instance of a model class.

When you use print() or display an instance of MyModel in the Django admin interface or any other place where string representation is required, the __str__() method is called automatically to generate the string representation of the object.




Property

@property
    def average_fossil_value(self):
        fossils = self.fossil_set.all()
        values = [f.fossil_value for f in fossils if f.fossil_value is not None]
        if values:
            return sum(values) / len(values)
        else:
            return None
        
    @property
    def total_fossil_value(self):
        total = DBFossil.objects.filter(fossil_species=self).aggregate(total_value=models.Sum('fossil_value'))['total_value']
        return total or 0
    
    @property
    def calculate_number_of_fossils(self):
        return DBFossil.objects.filter(fossil_species=self).count()

In Django models, the @property decorator is used to define derived or computed properties based on other attributes of the model. When you define a @property in a Django model, it creates a method that can be accessed as if it were a regular attribute of the model instance.

While @property is a very handy feature keep in mind that property is calculated every time it is accessed, whether directly or as part of a queryset or a model instance. Defining too many calculated properties can potentially slow down your application, especially if the calculations involve complex or time-consuming operations.




Choices

class DBFossil(models.Model):
    class Meta:
        ordering = ('fossil_name', )
        verbose_name = 'Fossil'
        verbose_name_plural = "Fossils"
  
    class FossilstatusChoices(models.TextChoices):
        COLLECTION = 'Collection', 'Collection'
        SOLD = 'Sold', 'Sold'
        LOAN = 'Loan' , 'Loan'
        DONATED = 'Donated', 'Donated'
        LOST = 'Lost', 'Lost'

In Django models, choices is a parameter that can be used to define a set of choices for a field. This is often used with CharField or IntegerField fields to restrict the values that can be stored in the field to a predefined set of options.

Using the choices parameter has several benefits. First, it can help ensure data consistency by restricting the possible values that can be stored in a field. Second, it can make your forms easier to use by providing clear and meaningful labels for each option. Finally, it can make your code more readable by using descriptive labels instead of raw values throughout your codebase.




auto_now_add and auto_now

fossil_entry_created = models.DateTimeField(auto_now_add=True)
fossil_entry_updated = models.DateTimeField(auto_now=True)

In Django models, auto_now_add and auto_now are parameters that can be used to automatically set the value of a DateTimeField to the current date and time when an object is created or saved.

The auto_now_add parameter is used to set the value of the field to the current date and time when the object is first created. After the object is created, the value will not be updated.

The auto_now parameter is used to set the value of the field to the current date and time every time the object is saved. The value will be automaticaly updated every time the object is saved.