brewery-website/yeast/models.py
Chris GIACOFEI 77354bfcbd Custom UUID field for yeast samples/batches.
Prepends date 'YYYYMMDD' to some random numbers.
2024-05-31 08:14:07 -04:00

155 lines
5.3 KiB
Python

from django.db import models
from django.utils import timezone
from django.utils.html import format_html
from datetime import datetime
from django.contrib.auth.models import User
from django.db.models import Count
import math
from config.extras import DateUUIDField
import logging
logger = logging.getLogger('django')
class AvailableYeastManager(models.Manager):
""" Special manager for filtering out pitched yeast."""
def get_queryset(self):
return super(AvailableYeastManager, self).get_queryset().filter(pitched=False)
class CustomModel(models.Model):
""" Custom model class with default fields to use. """
created_date = models.DateTimeField(default=timezone.now)
class Meta:
abstract = True
class Manufacturer(CustomModel):
""" Store manufacturer data for various yeast strains."""
name = models.CharField(max_length=100)
website = models.URLField(max_length=200, blank=True, null=True)
def __str__(self):
# Return a string that represents the instance
return self.name
class Strain(CustomModel):
"""
Store individual yeast strain data. :model:`yeast.Manufacturer`.
"""
name = models.CharField(max_length=100)
long_name = models.CharField(max_length=100, blank=True)
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.PROTECT)
def __str__(self):
# Return a string that represents the instance
return '{}: {}'.format(self.manufacturer.name, self.name)
class Storage(CustomModel):
"""
Data for methods of yeast storage. Used for calculating viability
in :model:`yeast.Yeast`.
"""
name = models.CharField(max_length=100)
viability_loss = models.DecimalField(max_digits=6, decimal_places=4)
viability_interval = models.IntegerField(default=30)
def __str__(self):
# Return a string that represents the instance
return self.name
class Batch(CustomModel):
"""
Stores a batch of :model:`yeast.Yeast` of a single :model:`yeast.Strain`.
Can be a single purchased pack, or multiple vials
to be frozen from a starter.
"""
BATCH_TYPES = {
'ST': 'Store',
'PR': 'Propogated',
'SL': 'Slurry',
}
id = DateUUIDField(primary_key=True)
parent = models.ManyToManyField('Yeast', related_name='+', blank=True)
production_date = models.DateField()
strain = models.ForeignKey(Strain, on_delete=models.PROTECT, default=0)
source = models.CharField(max_length=3, choices=BATCH_TYPES, default='ST')
source_batch = models.ForeignKey('beer.Batch', null=True, blank=True, on_delete=models.PROTECT)
notes = models.TextField(max_length=500, blank=True, null=True)
def save(self, *args, **kwargs):
super(Batch, self).save(*args, **kwargs)
if self.source_batch:
relate_samples = [x for x in Yeast.objects.all() if x.pitched_batch==self.source_batch]
for sample in relate_samples:
logger.critical(sample)
self.parent.add(sample)
@property
def consumed(self):
return not len(self.remaining_samples) > 0
@property
def remaining_samples(self):
return [x for x in Yeast.available.all() if x.batch==self]
def __str__(self):
# Return a string that represents the instance
return '{} [{}]'.format(self.strain, self.production_date.strftime("%Y-%m-%d"))
class Yeast(CustomModel):
"""
Store an individual sample of yeast.
"""
id = DateUUIDField(primary_key=True)
batch = models.ForeignKey(Batch, on_delete=models.CASCADE)
generation_num = models.IntegerField(default=0)
storage = models.ForeignKey(Storage, on_delete=models.CASCADE)
cellcount = models.IntegerField(default=100)
pitched = models.BooleanField(default=False)
date_pitched = models.DateField(blank=True, null=True)
pitched_batch = models.ForeignKey('beer.Batch', null=True, blank=True, on_delete=models.CASCADE)
data_web = models.URLField(blank=True, null=True)
lot_number = models.CharField(max_length=15, blank=True, null=True)
notes = models.TextField(max_length=500, blank=True, null=True)
objects = models.Manager()
available = AvailableYeastManager()
@property
def name(self):
return '{} {}'.format(self.id, self.batch.strain.name)
@property
def age(self):
"""Return the age in days since the sample was propogated."""
if self.pitched:
end_date = self.date_pitched
else:
end_date = timezone.now().date()
return abs((self.batch.production_date-end_date).days)
@property
def viability(self):
"""Return the viability based on age and storage method (:model:`yeast.Storage`)."""
return 0.97 * math.exp(self.age * math.log(1-self.storage.viability_loss)/self.storage.viability_interval)
def __str__(self):
# Return a string that represents the instance
return '{} {}'.format(self.id, self.batch.strain.name)
# class BeerBatch(CustomModel):
# brewfather_id = models.CharField(max_length=50)
# brewfather_num = models.IntegerField(default=1)
# brewfather_name = models.CharField(max_length=500, default='name')
# def __str__(self):
# # Return a string that represents the instance
# return 'BF #{num}: {name}'.format(name=self.brewfather_name, num=self.brewfather_num)