from django.db import models from django.contrib.auth.models import User from django.utils.encoding import python_2_unicode_compatible from django.utils.timezone import now #In order to run the database queries, there’s a manager for every model. # Unless it’s otherwise defined, the attribute objects holds a reference to the default manager. # The queries can be altered by overriding the default manager or adding another one. class PublicBookmarkManager(models.Manager): def get_queryset(self): qs = super(PublicBookmarkManager, self).get_queryset() return qs.filter(is_public=True) # Create your models here. # Models define how data is saved. Usually a model represents a table in the database, and has fields, metadata and methods @python_2_unicode_compatible class Tag(models.Model): name = models.CharField(max_length=50, unique=True) # Models can contain Metadata, that can influence how they are displayed or how they behave class Meta: verbose_name = 'tag' verbose_name_plural = 'tagS' ordering = ['name'] # You can now add Model functionality Methods for actions that apply to a single record. # For instance, it is usual to create a human readable form of the record with the method __str__. def __str__(self): return self.name @python_2_unicode_compatible class Bookmark(models.Model): url = models.URLField() title = models.CharField('title', max_length=255) description = models.TextField('description', blank=True) is_public = models.BooleanField('public', default=True) date_created = models.DateTimeField('date created') date_updated = models.DateTimeField('date updated') owner = models.ForeignKey(User, verbose_name='owner', related_name='bookmarks', on_delete=models.DO_NOTHING) tags = models.ManyToManyField(Tag, blank=True) # In our example we’ll often show only public bookmarks so we add a second manager to the Bookmark model that will only return the public bookmarks. # We’ll assign it to the attribute public. In order to keep a reference to the default manager, we have to explicitely assign it to the objects object = models.Manager() public = PublicBookmarkManager() class Meta: verbose_name = 'bookmark' verbose_name_plural = 'bookmarkS' ordering = ['-date_created'] def __str__(self): return '%s (%s)' % (self.title, self.url) #In the bookmark model, we’ll also override the method save() to set the right creation or last-changed date. # The state of the id field will be used, in order to decide if the model has already been saved or not. def save(self, *args, **kwargs): if not self.id: self.date_created =now() self.date_updated = now() super(Bookmark, self).save(*args, **kwargs)