Now we are going to use AnyBlok mixins to:
- Refactor our code in order to use
IdColumnmixin to create the id primary key column on the room model
- Use the
TrackModelmixin that adds 2 fields to track creation and last modification date:
Note: You can clone
III-03_create-modelbranch from AnyBlok/anyblok-book-examples repo to get ready to start with this chapter.
Add [anyblok_mixins][pypi_anyblok_mixins] to your package requirements and install the package.
file: setup.py requirements = [ 'anyblok', 'psycopg2', 'anyblok_pyramid', 'anyblok_address', + 'anyblok_mixins', ]
anyblok-mixins blok as required in the Room blok init file.
file: rooms_booking/room/__init__.py class Room(Blok): """Room's Blok class definition """ version = "0.1.0" author = "Pierre Verkest" - required = ['anyblok-core', 'address'] + required = ['anyblok-core', 'address', 'anyblok-mixins']
Add a unittest
In the following test we make sure as requested by our customer that
edit_date field is properly updated after a change occurs on a room.
#File: rooms_booking/room/tests/test_room.py from datetime import datetime import time import pytz class TestRoom(BlokTestCase): [...] def test_track_modification_date(self): before_create = datetime.now(tz=pytz.timezone(time.tzname)) room = self.registry.Room.insert( name="A1", capacity=25, ) room.refresh() after_create = datetime.now(tz=pytz.timezone(time.tzname)) room.name = "A2" self.registry.flush() after_edit = datetime.now(tz=pytz.timezone(time.tzname)) self.assertTrue( before_create <= room.create_date <= after_create ) self.assertTrue( after_create <= room.edit_date <= after_edit )
room.flush()is used here to force sending data to the database as
edit_datefield is configured with auto_update option wich is called before sending data to the database.
room.refresh()is used to clear cache on the ORM side to request data from the database. It will perform a flush before if necessary.
Those methods are rarely used in your code but can be tricky while playing with some kind of fields.
Using multiple inheritance capability we inherits from
from anyblok import Declarations from anyblok.column import String, Integer Model = Declarations.Model +Mixin = Declarations.Mixin + register = Declarations.register -class Room: +class Room(Mixin.IdColumn, Mixin.TrackModel): - id = Integer(primary_key=True) name = String(label="Room name", nullable=False, index=True) capacity = Integer(label="Capacity", nullable=False)