Related
def ran_gen(size, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
class StudentRoom(models.Model):
user_id = models.OneToOneField(StudentProfile, on_delete=models.CASCADE, null=True, blank=True)
property_room_id = models.ForeignKey(PropertyRoom, on_delete=models.CASCADE, max_length=50, blank=True, null=True)
student_hostel_code = models.CharField(max_length=6, default=ran_gen(6), editable=False)
note = models.CharField(max_length=50, blank=True, null=True)
allocated_date = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.student_hostel_code)
I want to make pay form, but I cannot show produk in orederitem, please helping me to show orderitem :v. I am really newbie in here .
models.py
class Order(models.Model):
name = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True)
order_data = models.DateTimeField(auto_now_add=True)
selesai = models.BooleanField(default=False, blank=True, null=True)
status = models.BooleanField(default=False, blank=True, null=True)
id_transaksi = models.CharField(max_length=200, null=True)
bukti = models.ImageField(null=True, blank=True)
ongkir = models.CharField(max_length=200, null=True)
total = models.CharField(max_length=200, null=True)
total_harga = models.CharField(max_length=200, null=True)
pembayaran = models.CharField(max_length=200, null=True)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0)
date_added = models.DateTimeField(auto_now_add=True)
views.py
def pembayaran(request):
customer = request.user.profile
ido = Order.objects.filter(id)
orders = Order.objects.filter(name=customer, selesai=True)
pengiriman = Pengiriman.objects.filter(name=customer)
OrderItems = OrderItem.objects.filter(order=ido)
print(OrderItems)
context = {'orders': orders,'pengiriman' :pengiriman , 'OrderItems': OrderItems }
return render(request, 'store/pembayaran.html', context)
I am performing a Django test case for models.py file the models.py file looks like
import sys
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django_google_maps import fields as map_fields
from django_mysql.models import ListTextField
from simple_history.models import HistoricalRecords
from farm_management import config
from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name
db_config = settings.USERS_DB_CONNECTION_CONFIG
class Device(models.Model):
id = models.CharField(max_length=100, primary_key=True)
fetch_status = models.BooleanField(default=True)
last_fetched_on = models.DateTimeField(auto_now=True)
geolocation = map_fields.GeoLocationField(max_length=100)
device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new')
is_active = models.BooleanField(default=True)
history = HistoricalRecords()
class Farm(models.Model):
farmer_id = models.PositiveIntegerField() # User for which farm is created
irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE)
soil_test_report = models.CharField(max_length=512, null=True, blank=True)
water_test_report = models.CharField(max_length=512, null=True, blank=True)
farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE)
franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE)
total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True,
validators=[MaxValueValidator(1000000), MinValueValidator(0)])
farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE)
assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned.
previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None)
sr_assignee_id = models.PositiveIntegerField(null=True, blank=True)
lgd_state_id = models.PositiveIntegerField(null=True, blank=True)
district_code = models.PositiveIntegerField(null=True, blank=True)
sub_district_code = models.PositiveIntegerField(null=True, blank=True)
village_code = models.PositiveIntegerField(null=True, blank=True)
farm_network_code = models.CharField(max_length=12, null=True, blank=True)
farm_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0.1)],
help_text="In Percentage", null=True, blank=True)
soil_k = models.FloatField(verbose_name="Soil (K)", null=True, blank=True)
soil_n = models.FloatField(verbose_name="Soil (N)", null=True, blank=True)
soil_p = models.FloatField(verbose_name="Soil (P)", null=True, blank=True)
water_ec = models.FloatField(verbose_name="Water (ec)", null=True, blank=True)
water_ph = models.FloatField(verbose_name="Water (pH)", null=True, blank=True)
soil_test_report_date = models.DateTimeField(null=True, blank=True)
water_test_report_date = models.DateTimeField(null=True, blank=True)
pest_problems = models.TextField(verbose_name="Pest Problems (If Any)", null=True, blank=True)
onboarded_by_id = models.PositiveIntegerField(null=True, blank=True)
farm_image = models.CharField(max_length=512, null=True, blank=True)
updated_by_id = models.PositiveIntegerField(null=True, blank=True)
created_by_id = models.PositiveIntegerField(null=True, blank=True)
device_id = models.ForeignKey(Device, on_delete=models.CASCADE, related_name="farm", null=True, blank=True,
db_column='device_id')
boundary_coord = models.TextField(verbose_name="Boundary of Farm", null=True, blank=True)
lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
lng = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
region_name = models.CharField(max_length=200, null=True, blank=True)
farmer_name = models.CharField(max_length=200, null=True, blank=True)
farm_name = models.CharField(max_length=200, null=True, blank=True)
pending_tasks = models.PositiveIntegerField(null=True, blank=True)
batch_count = models.PositiveIntegerField(default=0, null=True, blank=True)
locality = models.CharField(max_length=200, null=True, blank=True)
history = HistoricalRecords()
class Meta:
indexes = [
models.Index(fields=['farmer_id']),
models.Index(fields=['assignee_id']),
models.Index(fields=['sr_assignee_id'])
]
def __str__(self):
return self.farm_name
def save(self, *args, **kwargs):
if self.lgd_state_id:
region_name = get_region_name(self.lgd_state_id)
if region_name:
self.region_name = region_name[0]
if self.farmer_id:
farmer_name = get_farmer_name(self.farmer_id, 'name')
if not farmer_name.empty:
self.farmer_name = farmer_name[0]
self.farm_name = "{}'s farm".format(self.farmer_name)
if self.total_acerage:
self.farm_name += " - {} acres".format(self.total_acerage)
super(Farm, self).save(*args, **kwargs)
def update_pending_tasks(self):
BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement')
self.pending_tasks = BatchSOPManagement.objects.filter(batch_id__farm_id=self.id, current_status=2,
due_datetime__lt=datetime.today()).count()
self.save()
def update_batch_count(self):
Batch = apps.get_model('farm_management', 'Batch')
self.batch_count = Batch.objects.filter(farm_id=self.id).count()
self.save()
def update_farm_health(self):
Batch = apps.get_model('farm_management', 'Batch')
farm_health = [batch.batch_health * batch.acerage for batch in Batch.objects.filter(farm_id=self.id) if
batch.acerage and batch.batch_health]
total_acerage = sum([batch.acerage for batch in Batch.objects.filter(farm_id=self.id) if batch.acerage])
if total_acerage:
self.farm_health = sum(farm_health) / total_acerage
self.save()
class HistoricalCropInfo(models.Model):
historical_yield_per_acre = models.FloatField(verbose_name="Yield / Acre - Historical")
commodity_id = models.PositiveIntegerField()
commodity_variety_id = models.PositiveIntegerField(null=True, blank=True)
farm_id = models.ForeignKey(Farm, on_delete=models.CASCADE, related_name="hist_crops", db_column='farm_id')
history = HistoricalRecords()
class Batch(models.Model):
commodity_id = models.PositiveIntegerField(null=True, blank=True)
commodity_variety_id = models.PositiveIntegerField(null=True, blank=True)
farm_id = models.ForeignKey(Farm, on_delete=models.CASCADE, related_name="batches", null=True, blank=True,
db_column='farm_id')
start_date = models.DateTimeField(null=True, blank=True)
acerage = models.FloatField(verbose_name='Batch Acerage', help_text="In Acres;To change this value go to farms>crop"
, validators=[MaxValueValidator(1000000), MinValueValidator(0.01)])
batch_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0)],
help_text="In Percentage", default=100, null=True, blank=True)
stage = models.CharField(max_length=100, choices=config.STAGE_CHOICES, default='germination', null=True, blank=True)
expected_delivery_date = models.DateTimeField(null=True, blank=True)
current_pdd = models.FloatField(null=True, blank=True)
historic_pdd = models.FloatField(null=True, blank=True)
current_gdd = models.FloatField(null=True, blank=True)
historic_gdd = models.FloatField(null=True, blank=True)
sub_farmer_id = models.PositiveIntegerField(null=True, blank=True)
batch_status = models.CharField(max_length=100, choices=config.BATCH_STATUS, default='to_start')
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_by_id = models.PositiveIntegerField(null=True, blank=True)
created_by_id = models.PositiveIntegerField(null=True, blank=True)
historical_yield_per_acre = models.FloatField(verbose_name="Yield / Acre - Historical", null=True, blank=True)
expected_produce = models.FloatField(default=0, null=True, blank=True)
actual_produce = models.FloatField(default=0, null=True, blank=True)
sop_adherence = models.FloatField(default=0, null=True, blank=True)
actual_yield_per_acre = models.FloatField(default=0, null=True, blank=True)
end_date = models.DateTimeField(null=True, blank=True)
commodity_name = models.CharField(max_length=200, null=True, blank=True)
batch_name = models.CharField(max_length=200, null=True, blank=True)
batch_median_health = models.PositiveIntegerField(null=True, blank=True)
pending_tasks = models.PositiveIntegerField(null=True, blank=True, default=0)
history = HistoricalRecords()
def __str__(self):
return self.batch_name
def save(self, *args, **kwargs):
SOPMaster = apps.get_model('sop_management', 'SOPMaster')
BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement')
batch_sop_list = []
if self.batch_status is 'completed':
self.update_batch_end_date()
self.commodity_name = self.update_commodity_name()
self.batch_median_health = self.update_batch_median_health()
self.batch_name = self.update_batch_name()
super(Batch, self).save(*args, **kwargs)
def update_commodity_name(self):
if self.commodity_id:
commodity_name = get_commodity_name(self.commodity_id)
if commodity_name:
return commodity_name[0]
return None
def update_batch_median_health(self):
if self.start_date and self.expected_delivery_date:
start_date = datetime.combine(self.start_date, datetime.min.time())
expected_delivery_date = datetime.combine(self.expected_delivery_date, datetime.min.time())
end_date = min([expected_delivery_date, datetime.today()]) - relativedelta(hours=5, minutes=30)
hours_diff = int((((end_date - start_date).total_seconds()) / 3600 / 2))
median_date = start_date + relativedelta(hours=hours_diff)
try:
median_crop_health = self.history.as_of(median_date).crop_health
except:
median_crop_health = self.batch_health
return median_crop_health
else:
return None
def update_batch_name(self):
batch_name = "({}) {}".format(self.id, self.commodity_name)
if self.start_date:
batch_name += " | {}".format(self.start_date.strftime('%Y-%m-%d'))
return batch_name
def update_expected_delivery_date(self):
self.expected_delivery_date = max([batch_yield.expected_delivery_date for batch_yield in
self.batch_yields.all() if batch_yield.expected_delivery_date])
self.save()
def update_batch_status(self):
number_of_yields = self.batch_yields.all().count()
end_date_list = len([batch_yield for batch_yield in self.batch_yields.all() if
batch_yield.end_date and batch_yield.end_date.date() < datetime.today().date()])
if number_of_yields == end_date_list:
self.batch_status = 3
self.save()
def update_expected_produce(self):
self.expected_produce += sum([batch_yields.expected_production for batch_yields in self.batch_yields.all()
if not batch_yields.end_date])
self.save()
def update_actual_produce(self):
for batch_yields in self.batch_yields.all():
produce = 0
if batch_yields.grade_a_produce:
produce += batch_yields.grade_a_produce
if batch_yields.grade_b_produce:
produce += batch_yields.grade_b_produce
if batch_yields.grade_c_rejection:
produce += batch_yields.grade_c_rejection
self.actual_produce += produce
self.save()
def update_sop_adherence(self):
if self.batch_sop_management.all():
total_sop = self.batch_sop_management.filter(due_datetime__lte=datetime.today())
complete_sop = total_sop.filter(current_status=3)
if total_sop:
self.sop_adherence = complete_sop.count() / total_sop.count() * 100
self.save()
def update_actual_yield_per_acre(self):
batch_actual_produce = 0
for batch_yields in self.batch_yields.all():
actual_produce = 0
if batch_yields.end_date and batch_yields.end_date.date() <= datetime.today().date():
if batch_yields.grade_a_produce:
actual_produce += batch_yields.grade_a_produce
if batch_yields.grade_b_produce:
actual_produce += batch_yields.grade_b_produce
if batch_yields.grade_c_rejection:
actual_produce += batch_yields.grade_c_rejection
batch_actual_produce += actual_produce
if self.acerage and batch_actual_produce:
self.actual_yield_per_acre = batch_actual_produce / self.acerage
self.save()
def update_batch_end_date(self):
batch_yields = self.batch_yields.order_by('-end_date')
if batch_yields.exists():
batch_yields_id = batch_yields.filter(end_date__isnull=False)
if batch_yields_id.exists():
self.end_date = batch_yields[0].end_date
else:
self.end_date = datetime.now()
else:
raise ValidationError("Batch yield end date does not exists")
def update_pending_tasks(self):
BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement')
self.pending_tasks = BatchSOPManagement.objects.filter(batch_id=self.id, current_status=2,
due_datetime__lt=datetime.today()).count()
self.save()
class BatchYield(models.Model):
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_by_id = models.PositiveIntegerField(null=True, blank=True)
created_by_id = models.PositiveIntegerField(null=True, blank=True)
expected_production = models.FloatField(default=0, validators=[MaxValueValidator(1000000000), MinValueValidator(0)],
null=True, blank=True)
grade_a_produce = models.FloatField(verbose_name='Grade A - Produce', default=0, null=True, blank=True,
validators=[MaxValueValidator(1000000000), MinValueValidator(0)])
grade_b_produce = models.FloatField(verbose_name='Grade B - Produce', default=0, null=True, blank=True,
validators=[MaxValueValidator(1000000000), MinValueValidator(0)])
grade_c_rejection = models.FloatField(verbose_name='Grade C - Rejection', default=0, null=True, blank=True,
validators=[MaxValueValidator(1000000000), MinValueValidator(0)])
expected_delivery_date = models.DateTimeField()
batch_id = models.ForeignKey(Batch, on_delete=models.CASCADE, related_name="batch_yields", db_column='batch_id')
end_date = models.DateTimeField(help_text="Fill this date when this yield is realised with final date", null=True,
blank=True)
grade_a_sell_price = models.DecimalField(verbose_name='Grade A Sell Price', decimal_places=2, max_digits=7,
null=True, blank=True)
grade_b_sell_price = models.DecimalField(verbose_name='Grade B Sell Price', decimal_places=2, max_digits=7,
null=True, blank=True)
expected_grade_a_produce = models.DecimalField(decimal_places=2, max_digits=12, null=True, blank=True)
expected_grade_b_produce = models.DecimalField(decimal_places=2, max_digits=12, null=True, blank=True)
is_active = models.BooleanField(default=True)
history = HistoricalRecords()
def save(self, *args, **kwargs):
return super(BatchYield, self).save(*args, **kwargs)
def update_expected_grade_produce(self):
batch_median_health = self.batch_id.batch_median_health
if batch_median_health:
if batch_median_health == 100:
grade_a_percentage = 60
grade_b_percentage = 40
elif 90 <= batch_median_health < 100:
grade_a_percentage = 50
grade_b_percentage = 50
elif 85 <= batch_median_health < 90:
grade_a_percentage = 45
grade_b_percentage = 55
elif 80 <= batch_median_health < 85:
grade_a_percentage = 40
grade_b_percentage = 60
elif 70 <= batch_median_health < 80:
grade_a_percentage = 30
grade_b_percentage = 70
elif 65 <= batch_median_health < 70:
grade_a_percentage = 20
grade_b_percentage = 80
else:
grade_a_percentage = 0
grade_b_percentage = 100
self.expected_grade_a_produce = grade_a_percentage * self.expected_production / 100
self.expected_grade_b_produce = grade_b_percentage * self.expected_production / 100
self.save()
class batchActualProduce(models.Model):
harvest_date = models.DateField()
batch_produce = models.PositiveIntegerField(null=True, blank=True)
grade = models.CharField(max_length=10, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
batch_id = models.ForeignKey(Batch, on_delete=models.CASCADE, related_name="batch_produce", db_column='batch_id')
class Microbes(models.Model):
microbe_id = models.AutoField(primary_key=True)
product_code = models.CharField(max_length=50, unique=True)
beneficial_organism = models.TextField("beneficial_organism", null=True, blank=True)
product_nomenclature = models.TextField("product_nomenclature", null=True, blank=True)
utilization = models.TextField("uti", null=True, blank=True)
yield_increase = models.CharField(max_length=50)
savings = models.CharField(max_length=50)
fk_crop_id = models.IntegerField()
fk_region_id = models.IntegerField()
recommended_utilization = models.CharField(max_length=50, null=True, blank=True)
status = models.IntegerField(null=True, blank=True, default=True)
remedy = models.CharField(max_length=200, null=True, blank=True)
history = HistoricalRecords()
class Meta:
db_table = "microbes"
#property
def region_name(self):
"""function to return region_name based on lgd_state_id"""
if self.fk_region_id:
region_name = get_region_name(self.fk_region_id)
if region_name:
return region_name[0]
return None
#property
def commodity_name(self):
"""function to return commodity_name based on commodity_id"""
if self.fk_crop_id:
commodity_name = get_commodity_name(self.fk_crop_id)
if commodity_name:
return commodity_name[0]
return None
#property
def remedy_name(self):
"""function to return commodity_name based on commodity_id"""
remedy_name = ""
if self.remedy:
remedy_id_list = str(self.remedy).split(",")
remedy_name = ",".join(x.name for x in OrganismMapping.objects.filter(id__in=remedy_id_list))
return remedy_name
class MicrobesMapping(models.Model):
id = models.AutoField(primary_key=True)
microbe_id = models.ForeignKey(Microbes, on_delete=models.CASCADE, related_name="microbes_mapping",
db_column='microbe_id')
zone_com_microbe_id = models.CharField(max_length=200, null=True, blank=True)
remedy = models.TextField(null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(null=True, blank=True)
history = HistoricalRecords()
class OrganismMapping(models.Model):
id = models.AutoField(primary_key=True)
name = models.TextField()
status = models.IntegerField(null=True, blank=True)
history = HistoricalRecords()
class CropAttributes(models.Model):
commodity_id = models.PositiveIntegerField()
state_id = models.PositiveIntegerField()
variety_id = models.PositiveIntegerField(null=True, blank=True)
season_id = models.PositiveIntegerField(null=True, blank=True)
attribute_value = models.FloatField()
attribute_name = models.CharField(max_length=255, null=True, blank=True)
attribute_unit = models.CharField(max_length=50, null=True, blank=True)
status = models.BooleanField(default=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
#property
def commodity_name(self):
"""
function to return commodity_name based on commodity_id
"""
if self.commodity_id:
commodity_name = get_commodity_name(self.commodity_id)
if commodity_name:
return commodity_name[0]
return None
#property
def state_name(self):
"""
function to return region_name based on lgd_state_id
"""
if self.state_id:
state_name = get_region_name(self.state_id)
if state_name:
return state_name[0]
return None
#property
def variety_name(self):
"""
function to return variety_name based on variety_id
"""
if self.variety_id:
variety_name = get_variety_name(self.variety_id)
if variety_name:
return variety_name[0]
return None
class CropAttributesMaster(models.Model):
name = models.CharField(max_length=255, null=True, blank=True)
unit = models.CharField(max_length=50, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
#receiver([post_save, post_delete], sender=BatchYield)
def expected_delivery_date_update(sender, instance, **kwargs):
try:
sys.setrecursionlimit(120)
instance.batch_id.update_expected_delivery_date()
instance.batch_id.update_batch_status()
# instance.batch_id.update_expected_produce()
instance.batch_id.update_actual_produce()
instance.batch_id.update_sop_adherence()
instance.batch_id.update_actual_yield_per_acre()
instance.update_expected_grade_produce()
except:
pass
#receiver([post_save, post_delete], sender=Batch)
def update_batch_count(sender, instance, **kwargs):
instance.farm_id.update_batch_count()
#receiver(post_save, sender=Batch)
def update_farm_health(sender, instance, **kwargs):
instance.farm_id.update_farm_health()
for models.py file first I am testing the Batch class
in test_batch.py file which looks like
from datetime import datetime
from django import apps
from django.dispatch import receiver
from django.test import TestCase
from django.db.utils import IntegrityError
from django.db.models.signals import post_save, post_delete
from farm_management.models import Farm, Device, BatchYield, Batch
from sop_management.models import BatchSOPManagement
class TestBatch(TestCase):
def setUp(self):
self.batch1 = Batch.objects.create(
batch_name="(907) Cucumber | 2021-08-21",
acerage="4",
commodity_name="Cucumber"
)
self.farm_id = Farm.objects.create(farmer_id="106", batch_count="1")
def test_update_batch_name(self):
for i in range(5):
Batch.objects.create(farm_id=self.farm_id, commodity_name="Cucumber")
self.batch1.update_batch_name()
assert self.batch1.batch_name == 5
def test_batch(self):
self.assertEqual(self.batch1.batch_name, "(907) Cucumber | 2021-08-21")
self.assertEqual(self.batch1.acerage, "4")
self.assertEqual(self.farm_id.farmer_id, "106")
self.assertEqual(self.batch1.commodity_name, "Cucumber")
def test_return(self):
batch11 = Batch.objects.create(batch_name="(907) Cucumber | 2021-08-21", acerage="4")
batch11.save()
self.assertEqual(str(batch11), "(907) Cucumber | 2021-08-21")
def test_batch_count(self):
for i in range(1):
Batch.objects.create(farm_id=self.farm_id, acerage="4")
self.batch1.update_batch_count()
assert self.batch1.batch_count == 1
while performing the testing of batch class everytime I am getting the same error
the error looks
ERROR: test_update_batch_name (farm_management.test.models.test_batch.TestBatch)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/admin123/igrow-api/app/farm_management/test/models/test_batch.py", line 14, in setUp
self.batch1 = Batch.objects.create(
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/db/models/query.py", line 453, in create
obj.save(force_insert=True, using=self.db)
File "/home/admin123/igrow-api/app/farm_management/models.py", line 179, in save
super(Batch, self).save(*args, **kwargs)
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/db/models/base.py", line 774, in save_base
post_save.send(
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send
return [
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "/home/admin123/igrow-api/app/farm_management/models.py", line 482, in update_batch_count
instance.farm_id.update_batch_count()
AttributeError: 'NoneType' object has no attribute 'update_batch_count'
----------------------------------------------------------------------
Ran 1 test in 0.007s
FAILED (errors=1)
Destroying test database for alias 'default'...
I am testing the testing the models.py file which contain two class one is Farm and another one is Batch
and Batch has a foreign key related to farm
while testing the batch I have tested all the other columns but not sure how should I test the foreign key column of batch class
models.py file lopoks like
import sys
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django_google_maps import fields as map_fields
from django_mysql.models import ListTextField
from simple_history.models import HistoricalRecords
from farm_management import config
from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name
db_config = settings.USERS_DB_CONNECTION_CONFIG
class Device(models.Model):
id = models.CharField(max_length=100, primary_key=True)
fetch_status = models.BooleanField(default=True)
last_fetched_on = models.DateTimeField(auto_now=True)
geolocation = map_fields.GeoLocationField(max_length=100)
device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new')
is_active = models.BooleanField(default=True)
history = HistoricalRecords()
class Farm(models.Model):
farmer_id = models.PositiveIntegerField() # User for which farm is created
irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE)
soil_test_report = models.CharField(max_length=512, null=True, blank=True)
water_test_report = models.CharField(max_length=512, null=True, blank=True)
farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE)
franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE)
total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True,
validators=[MaxValueValidator(1000000), MinValueValidator(0)])
farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE)
assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned.
previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None)
sr_assignee_id = models.PositiveIntegerField(null=True, blank=True)
lgd_state_id = models.PositiveIntegerField(null=True, blank=True)
district_code = models.PositiveIntegerField(null=True, blank=True)
sub_district_code = models.PositiveIntegerField(null=True, blank=True)
village_code = models.PositiveIntegerField(null=True, blank=True)
farm_network_code = models.CharField(max_length=12, null=True, blank=True)
farm_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0.1)],
help_text="In Percentage", null=True, blank=True)
soil_k = models.FloatField(verbose_name="Soil (K)", null=True, blank=True)
soil_n = models.FloatField(verbose_name="Soil (N)", null=True, blank=True)
soil_p = models.FloatField(verbose_name="Soil (P)", null=True, blank=True)
water_ec = models.FloatField(verbose_name="Water (ec)", null=True, blank=True)
water_ph = models.FloatField(verbose_name="Water (pH)", null=True, blank=True)
soil_test_report_date = models.DateTimeField(null=True, blank=True)
water_test_report_date = models.DateTimeField(null=True, blank=True)
pest_problems = models.TextField(verbose_name="Pest Problems (If Any)", null=True, blank=True)
onboarded_by_id = models.PositiveIntegerField(null=True, blank=True)
farm_image = models.CharField(max_length=512, null=True, blank=True)
updated_by_id = models.PositiveIntegerField(null=True, blank=True)
created_by_id = models.PositiveIntegerField(null=True, blank=True)
device_id = models.ForeignKey(Device, on_delete=models.CASCADE, related_name="farm", null=True, blank=True,
db_column='device_id')
boundary_coord = models.TextField(verbose_name="Boundary of Farm", null=True, blank=True)
lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
lng = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
region_name = models.CharField(max_length=200, null=True, blank=True)
farmer_name = models.CharField(max_length=200, null=True, blank=True)
farm_name = models.CharField(max_length=200, null=True, blank=True)
pending_tasks = models.PositiveIntegerField(null=True, blank=True)
batch_count = models.PositiveIntegerField(default=0, null=True, blank=True)
locality = models.CharField(max_length=200, null=True, blank=True)
history = HistoricalRecords()
class Meta:
indexes = [
models.Index(fields=['farmer_id']),
models.Index(fields=['assignee_id']),
models.Index(fields=['sr_assignee_id'])
]
def __str__(self):
return self.farm_name
def save(self, *args, **kwargs):
if self.lgd_state_id:
region_name = get_region_name(self.lgd_state_id)
if region_name:
self.region_name = region_name[0]
if self.farmer_id:
farmer_name = get_farmer_name(self.farmer_id, 'name')
if not farmer_name.empty:
self.farmer_name = farmer_name[0]
self.farm_name = "{}'s farm".format(self.farmer_name)
if self.total_acerage:
self.farm_name += " - {} acres".format(self.total_acerage)
super(Farm, self).save(*args, **kwargs)
def update_pending_tasks(self):
BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement')
self.pending_tasks = BatchSOPManagement.objects.filter(batch_id__farm_id=self.id, current_status=2,
due_datetime__lt=datetime.today()).count()
self.save()
def update_batch_count(self):
Batch = apps.get_model('farm_management', 'Batch')
self.batch_count = Batch.objects.filter(farm_id=self.id).count()
self.save()
def update_farm_health(self):
Batch = apps.get_model('farm_management', 'Batch')
farm_health = [batch.batch_health * batch.acerage for batch in Batch.objects.filter(farm_id=self.id) if
batch.acerage and batch.batch_health]
total_acerage = sum([batch.acerage for batch in Batch.objects.filter(farm_id=self.id) if batch.acerage])
if total_acerage:
self.farm_health = sum(farm_health) / total_acerage
self.save()
class HistoricalCropInfo(models.Model):
historical_yield_per_acre = models.FloatField(verbose_name="Yield / Acre - Historical")
commodity_id = models.PositiveIntegerField()
commodity_variety_id = models.PositiveIntegerField(null=True, blank=True)
farm_id = models.ForeignKey(Farm, on_delete=models.CASCADE, related_name="hist_crops", db_column='farm_id')
history = HistoricalRecords()
class Batch(models.Model):
commodity_id = models.PositiveIntegerField(null=True, blank=True)
commodity_variety_id = models.PositiveIntegerField(null=True, blank=True)
farm_id = models.ForeignKey(Farm, on_delete=models.CASCADE, related_name="batches", null=True, blank=True,
db_column='farm_id')
start_date = models.DateTimeField(null=True, blank=True)
acerage = models.FloatField(verbose_name='Batch Acerage', help_text="In Acres;To change this value go to farms>crop"
, validators=[MaxValueValidator(1000000), MinValueValidator(0.01)])
batch_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0)],
help_text="In Percentage", default=100, null=True, blank=True)
stage = models.CharField(max_length=100, choices=config.STAGE_CHOICES, default='germination', null=True, blank=True)
expected_delivery_date = models.DateTimeField(null=True, blank=True)
current_pdd = models.FloatField(null=True, blank=True)
historic_pdd = models.FloatField(null=True, blank=True)
current_gdd = models.FloatField(null=True, blank=True)
historic_gdd = models.FloatField(null=True, blank=True)
sub_farmer_id = models.PositiveIntegerField(null=True, blank=True)
batch_status = models.CharField(max_length=100, choices=config.BATCH_STATUS, default='to_start')
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_by_id = models.PositiveIntegerField(null=True, blank=True)
created_by_id = models.PositiveIntegerField(null=True, blank=True)
historical_yield_per_acre = models.FloatField(verbose_name="Yield / Acre - Historical", null=True, blank=True)
expected_produce = models.FloatField(default=0, null=True, blank=True)
actual_produce = models.FloatField(default=0, null=True, blank=True)
sop_adherence = models.FloatField(default=0, null=True, blank=True)
actual_yield_per_acre = models.FloatField(default=0, null=True, blank=True)
end_date = models.DateTimeField(null=True, blank=True)
commodity_name = models.CharField(max_length=200, null=True, blank=True)
batch_name = models.CharField(max_length=200, null=True, blank=True)
batch_median_health = models.PositiveIntegerField(null=True, blank=True)
pending_tasks = models.PositiveIntegerField(null=True, blank=True, default=0)
history = HistoricalRecords()
def __str__(self):
return self.batch_name
def save(self, *args, **kwargs):
SOPMaster = apps.get_model('sop_management', 'SOPMaster')
BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement')
batch_sop_list = []
if self.batch_status is 'completed':
self.update_batch_end_date()
self.commodity_name = self.update_commodity_name()
self.batch_median_health = self.update_batch_median_health()
self.batch_name = self.update_batch_name()
super(Batch, self).save(*args, **kwargs)
def update_commodity_name(self):
if self.commodity_id:
commodity_name = get_commodity_name(self.commodity_id)
if commodity_name:
return commodity_name[0]
return None
def update_batch_median_health(self):
if self.start_date and self.expected_delivery_date:
start_date = datetime.combine(self.start_date, datetime.min.time())
expected_delivery_date = datetime.combine(self.expected_delivery_date, datetime.min.time())
end_date = min([expected_delivery_date, datetime.today()]) - relativedelta(hours=5, minutes=30)
hours_diff = int((((end_date - start_date).total_seconds()) / 3600 / 2))
median_date = start_date + relativedelta(hours=hours_diff)
try:
median_crop_health = self.history.as_of(median_date).crop_health
except:
median_crop_health = self.batch_health
return median_crop_health
else:
return None
def update_batch_name(self):
batch_name = "({}) {}".format(self.id, self.commodity_name)
if self.start_date:
batch_name += " | {}".format(self.start_date.strftime('%Y-%m-%d'))
return batch_name
def update_expected_delivery_date(self):
self.expected_delivery_date = max([batch_yield.expected_delivery_date for batch_yield in
self.batch_yields.all() if batch_yield.expected_delivery_date])
self.save()
def update_batch_status(self):
number_of_yields = self.batch_yields.all().count()
end_date_list = len([batch_yield for batch_yield in self.batch_yields.all() if
batch_yield.end_date and batch_yield.end_date.date() < datetime.today().date()])
if number_of_yields == end_date_list:
self.batch_status = 3
self.save()
def update_expected_produce(self):
self.expected_produce += sum([batch_yields.expected_production for batch_yields in self.batch_yields.all()
if not batch_yields.end_date])
self.save()
def update_actual_produce(self):
for batch_yields in self.batch_yields.all():
produce = 0
if batch_yields.grade_a_produce:
produce += batch_yields.grade_a_produce
if batch_yields.grade_b_produce:
produce += batch_yields.grade_b_produce
if batch_yields.grade_c_rejection:
produce += batch_yields.grade_c_rejection
self.actual_produce += produce
self.save()
def update_sop_adherence(self):
if self.batch_sop_management.all():
total_sop = self.batch_sop_management.filter(due_datetime__lte=datetime.today())
complete_sop = total_sop.filter(current_status=3)
if total_sop:
self.sop_adherence = complete_sop.count() / total_sop.count() * 100
self.save()
def update_actual_yield_per_acre(self):
batch_actual_produce = 0
for batch_yields in self.batch_yields.all():
actual_produce = 0
if batch_yields.end_date and batch_yields.end_date.date() <= datetime.today().date():
if batch_yields.grade_a_produce:
actual_produce += batch_yields.grade_a_produce
if batch_yields.grade_b_produce:
actual_produce += batch_yields.grade_b_produce
if batch_yields.grade_c_rejection:
actual_produce += batch_yields.grade_c_rejection
batch_actual_produce += actual_produce
if self.acerage and batch_actual_produce:
self.actual_yield_per_acre = batch_actual_produce / self.acerage
self.save()
def update_batch_end_date(self):
batch_yields = self.batch_yields.order_by('-end_date')
if batch_yields.exists():
batch_yields_id = batch_yields.filter(end_date__isnull=False)
if batch_yields_id.exists():
self.end_date = batch_yields[0].end_date
else:
self.end_date = datetime.now()
else:
raise ValidationError("Batch yield end date does not exists")
def update_pending_tasks(self):
BatchSOPManagement = apps.get_model('sop_management', 'BatchSOPManagement')
self.pending_tasks = BatchSOPManagement.objects.filter(batch_id=self.id, current_status=2,
due_datetime__lt=datetime.today()).count()
self.save()
class BatchYield(models.Model):
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_by_id = models.PositiveIntegerField(null=True, blank=True)
created_by_id = models.PositiveIntegerField(null=True, blank=True)
expected_production = models.FloatField(default=0, validators=[MaxValueValidator(1000000000), MinValueValidator(0)],
null=True, blank=True)
grade_a_produce = models.FloatField(verbose_name='Grade A - Produce', default=0, null=True, blank=True,
validators=[MaxValueValidator(1000000000), MinValueValidator(0)])
grade_b_produce = models.FloatField(verbose_name='Grade B - Produce', default=0, null=True, blank=True,
validators=[MaxValueValidator(1000000000), MinValueValidator(0)])
grade_c_rejection = models.FloatField(verbose_name='Grade C - Rejection', default=0, null=True, blank=True,
validators=[MaxValueValidator(1000000000), MinValueValidator(0)])
expected_delivery_date = models.DateTimeField()
batch_id = models.ForeignKey(Batch, on_delete=models.CASCADE, related_name="batch_yields", db_column='batch_id')
end_date = models.DateTimeField(help_text="Fill this date when this yield is realised with final date", null=True,
blank=True)
grade_a_sell_price = models.DecimalField(verbose_name='Grade A Sell Price', decimal_places=2, max_digits=7,
null=True, blank=True)
grade_b_sell_price = models.DecimalField(verbose_name='Grade B Sell Price', decimal_places=2, max_digits=7,
null=True, blank=True)
expected_grade_a_produce = models.DecimalField(decimal_places=2, max_digits=12, null=True, blank=True)
expected_grade_b_produce = models.DecimalField(decimal_places=2, max_digits=12, null=True, blank=True)
is_active = models.BooleanField(default=True)
history = HistoricalRecords()
def save(self, *args, **kwargs):
return super(BatchYield, self).save(*args, **kwargs)
def update_expected_grade_produce(self):
batch_median_health = self.batch_id.batch_median_health
if batch_median_health:
if batch_median_health == 100:
grade_a_percentage = 60
grade_b_percentage = 40
elif 90 <= batch_median_health < 100:
grade_a_percentage = 50
grade_b_percentage = 50
elif 85 <= batch_median_health < 90:
grade_a_percentage = 45
grade_b_percentage = 55
elif 80 <= batch_median_health < 85:
grade_a_percentage = 40
grade_b_percentage = 60
elif 70 <= batch_median_health < 80:
grade_a_percentage = 30
grade_b_percentage = 70
elif 65 <= batch_median_health < 70:
grade_a_percentage = 20
grade_b_percentage = 80
else:
grade_a_percentage = 0
grade_b_percentage = 100
self.expected_grade_a_produce = grade_a_percentage * self.expected_production / 100
self.expected_grade_b_produce = grade_b_percentage * self.expected_production / 100
self.save()
class batchActualProduce(models.Model):
harvest_date = models.DateField()
batch_produce = models.PositiveIntegerField(null=True, blank=True)
grade = models.CharField(max_length=10, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
batch_id = models.ForeignKey(Batch, on_delete=models.CASCADE, related_name="batch_produce", db_column='batch_id')
class Microbes(models.Model):
microbe_id = models.AutoField(primary_key=True)
product_code = models.CharField(max_length=50, unique=True)
beneficial_organism = models.TextField("beneficial_organism", null=True, blank=True)
product_nomenclature = models.TextField("product_nomenclature", null=True, blank=True)
utilization = models.TextField("uti", null=True, blank=True)
yield_increase = models.CharField(max_length=50)
savings = models.CharField(max_length=50)
fk_crop_id = models.IntegerField()
fk_region_id = models.IntegerField()
recommended_utilization = models.CharField(max_length=50, null=True, blank=True)
status = models.IntegerField(null=True, blank=True, default=True)
remedy = models.CharField(max_length=200, null=True, blank=True)
history = HistoricalRecords()
class Meta:
db_table = "microbes"
#property
def region_name(self):
"""function to return region_name based on lgd_state_id"""
if self.fk_region_id:
region_name = get_region_name(self.fk_region_id)
if region_name:
return region_name[0]
return None
#property
def commodity_name(self):
"""function to return commodity_name based on commodity_id"""
if self.fk_crop_id:
commodity_name = get_commodity_name(self.fk_crop_id)
if commodity_name:
return commodity_name[0]
return None
#property
def remedy_name(self):
"""function to return commodity_name based on commodity_id"""
remedy_name = ""
if self.remedy:
remedy_id_list = str(self.remedy).split(",")
remedy_name = ",".join(x.name for x in OrganismMapping.objects.filter(id__in=remedy_id_list))
return remedy_name
class MicrobesMapping(models.Model):
id = models.AutoField(primary_key=True)
microbe_id = models.ForeignKey(Microbes, on_delete=models.CASCADE, related_name="microbes_mapping",
db_column='microbe_id')
zone_com_microbe_id = models.CharField(max_length=200, null=True, blank=True)
remedy = models.TextField(null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(null=True, blank=True)
history = HistoricalRecords()
class OrganismMapping(models.Model):
id = models.AutoField(primary_key=True)
name = models.TextField()
status = models.IntegerField(null=True, blank=True)
history = HistoricalRecords()
class CropAttributes(models.Model):
commodity_id = models.PositiveIntegerField()
state_id = models.PositiveIntegerField()
variety_id = models.PositiveIntegerField(null=True, blank=True)
season_id = models.PositiveIntegerField(null=True, blank=True)
attribute_value = models.FloatField()
attribute_name = models.CharField(max_length=255, null=True, blank=True)
attribute_unit = models.CharField(max_length=50, null=True, blank=True)
status = models.BooleanField(default=True, null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
#property
def commodity_name(self):
"""
function to return commodity_name based on commodity_id
"""
if self.commodity_id:
commodity_name = get_commodity_name(self.commodity_id)
if commodity_name:
return commodity_name[0]
return None
#property
def state_name(self):
"""
function to return region_name based on lgd_state_id
"""
if self.state_id:
state_name = get_region_name(self.state_id)
if state_name:
return state_name[0]
return None
#property
def variety_name(self):
"""
function to return variety_name based on variety_id
"""
if self.variety_id:
variety_name = get_variety_name(self.variety_id)
if variety_name:
return variety_name[0]
return None
class CropAttributesMaster(models.Model):
name = models.CharField(max_length=255, null=True, blank=True)
unit = models.CharField(max_length=50, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
#receiver([post_save, post_delete], sender=BatchYield)
def expected_delivery_date_update(sender, instance, **kwargs):
try:
sys.setrecursionlimit(120)
instance.batch_id.update_expected_delivery_date()
instance.batch_id.update_batch_status()
# instance.batch_id.update_expected_produce()
instance.batch_id.update_actual_produce()
instance.batch_id.update_sop_adherence()
instance.batch_id.update_actual_yield_per_acre()
instance.update_expected_grade_produce()
except:
pass
#receiver([post_save, post_delete], sender=Batch)
def update_batch_count(sender, instance, **kwargs):
instance.farm_id.update_batch_count()
#receiver(post_save, sender=Batch)
def update_farm_health(sender, instance, **kwargs):
instance.farm_id.update_farm_health()
and the class that i am tersting right now is Batch
and test file of batch looks like
from django.test import TestCase
from django.db.utils import IntegrityError
from farm_management.models import Farm, Device, BatchYield, Batch
class TestBatch(TestCase):
def setUp(self):
self.batch1 = Batch.objects.create(
commodity_id="2",
commodity_variety_id="4",
acerage="90",
batch_health="100",
stage="germination",
batch_status="running",
updated_at="2021-11-26 09:27:18.464511",
created_at="2021-11-26 08:50:26.618932",
updated_by_id="1224",
created_by_id="1224",
#batch_name="(1) Apple | 2021-11-26",
commodity_name="Apple",
#start_date="2021-11-26 14:20:14.000000"
)
self.farmid = Farm.objects.get(farmer_id="1")
def test_farm(self):
self.assertEqual(self.batch1.commodity_id, "2")
self.assertEqual(self.batch1.commodity_variety_id, "4")
self.assertEqual(self.batch1.acerage, "90")
self.assertEqual(self.batch1.batch_health, "100")
self.assertEqual(self.batch1.stage, "germination")
self.assertEqual(self.batch1.batch_status, "running")
self.assertEqual(self.batch1.updated_at, "2021-11-26 09:27:18.464511")
self.assertEqual(self.batch1.created_at, "2021-11-26 08:50:26.618932")
self.assertEqual(self.batch1.updated_by_id, "1224")
self.assertEqual(self.batch1.created_by_id, "1224")
self.assertEqual(self.batch1.batch_name, "(1) Apple | 2021-11-26")
self.assertEqual(self.batch1.commodity_name, "Apple")
self.assertEqual(self.batch1.start_date, "2021-11-26 14:20:14.000000")
self.assertEqual((self.farmid.farmer_id, "1"))
But this testing code giving error
/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/storages/backends/s3boto3.py:282: UserWarning: The default behavior of S3Boto3Storage is insecure and will change in django-storages 2.0. By default files and new buckets are saved with an ACL of 'public-read' (globally publicly readable). Version 2.0 will default to using the bucket's ACL. To opt into the new behavior set AWS_DEFAULT_ACL = None, otherwise to silence this warning explicitly set AWS_DEFAULT_ACL.
warnings.warn(
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_farm (farm_management.test.models.batch.TestBatch)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/admin123/igrow-api/app/farm_management/test/models/batch.py", line 10, in setUp
self.batch1 = Batch.objects.create(
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/db/models/query.py", line 453, in create
obj.save(force_insert=True, using=self.db)
File "/home/admin123/igrow-api/app/farm_management/models.py", line 179, in save
super(Batch, self).save(*args, **kwargs)
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/db/models/base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/db/models/base.py", line 774, in save_base
post_save.send(
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send
return [
File "/home/admin123/igrow-api/igrow-api-backend/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp>
(receiver, receiver(signal=self, sender=sender, **named))
File "/home/admin123/igrow-api/app/farm_management/models.py", line 482, in update_batch_count
instance.farm_id.update_batch_count()
AttributeError: 'NoneType' object has no attribute 'update_batch_count'
----------------------------------------------------------------------
Ran 1 test in 0.527s
FAILED (errors=1)
Destroying test database for alias 'default'...
and update_batch_count is in farm class
def update_batch_count(self):
Batch = apps.get_model('farm_management', 'Batch')
self.batch_count = Batch.objects.filter(farm_id=self.id).count()
self.save()
and bacth_count is a column of fram class
I've been asked to design a way for people to search through multiple models on criteria they enter and allow them to export any number of fields they select.
Example:
User enters "Teacher" as a term for Job Title and "Google" for a Work Site Location but want to export "Employee ID", "First Name", "Last Name", "Date of Birth"
I'm sure this is possible, but I'm at a complete loss for where to start.
My models (for reference) are here:
import datetime
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.utils import timezone
class Classification(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Classification Name')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Classification'
verbose_name = 'Classification'
verbose_name_plural = 'Classifications'
class Location(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name')
aeries_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='Aeries ID')
county_id = models.CharField(max_length=25, blank=True, null=True, verbose_name='County ID')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Location'
verbose_name = 'Location'
verbose_name_plural = 'Locations'
ordering = ['name']
class Person(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True)
current_identity = models.ForeignKey('PersonIdentity', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Current Identity', related_name='current_identity')
employee_id = models.CharField(max_length=255, null=False, blank=False, verbose_name='Employee ID')
birthdate = models.DateField(blank=True, null=True, verbose_name='Birthdate')
original_hire_date = models.DateField(blank=True, null=True, verbose_name='Original Hire Date')
def __str__(self):
if self.current_identity is not None:
return '{}'.format(str(self.current_identity))
else:
return "{}".format(self.employee_id)
#property
def current_age(self):
from dateutil.relativedelta import relativedelta
difference_in_years = relativedelta(timezone.now().date(), self.birthdate).years
return difference_in_years
def primary_assignment(self):
return self.jobassignment_set.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).order_by('priority')[0]
#property
def display_name(self):
if self.current_identity:
return '{0.first_name} {0.last_name} ({1.employee_id})'.format(self.current_identity, self)
else:
return 'Employee ID {0.employee_id}'.format(self)
#property
def is_certificated(self):
assignments = JobAssignment.objects.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).filter(
person=self,
classification__name__icontains="Certificated"
)
return assignments.count() >= 1
class Meta:
db_table = 'Person'
verbose_name = 'Person'
verbose_name_plural = 'People'
class PersonIdentity(models.Model):
person = models.ForeignKey(Person, verbose_name='Person', on_delete=models.CASCADE)
first_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='First Name')
middle_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='Middle Name')
last_name = models.CharField(max_length=50, blank=True, null=True, verbose_name='Last Name')
start_date = models.DateField(blank=False, null=False, default=datetime.date.today, verbose_name='Start Date')
end_date = models.DateField(blank=True, null=True, verbose_name='End Date')
def __str__(self):
first_name = '' if self.first_name is None else self.first_name
last_name = '' if self.last_name is None else self.last_name
if self.middle_name is not None and self.middle_name != '':
return "{} {}. {} ({})".format(first_name, self.middle_name[0], last_name, self.person.employee_id)
else:
return "{} {} ({})".format(first_name, last_name, self.person.employee_id)
def save(self, *args, **kwargs):
change_identity = False
if not self.id:
change_identity = True
super().save(*args, **kwargs)
if change_identity:
self.person.current_identity = self
self.person.save()
class Meta:
db_table = 'PersonIdentity'
verbose_name = 'Person Identity'
verbose_name_plural = 'Person Identities'
ordering = ['end_date', 'last_name', 'first_name']
class Contact(models.Model):
person = models.OneToOneField(Person, on_delete=models.CASCADE, verbose_name='Person')
email_address = models.EmailField(blank=True, null=True, verbose_name='Primary Email')
phone_number = models.CharField(max_length=15, blank=True, null=True, verbose_name='Phone Number')
phone_extension = models.CharField(max_length=255, blank=True, null=True, verbose_name='Phone Extension')
address1 = models.CharField(max_length=255, blank=True, null=True, verbose_name='Address 1')
address2 = models.CharField(max_length=255, blank=True, null=True, verbose_name='Address 2')
city = models.CharField(max_length=255, blank=True, null=True, verbose_name='City')
state = models.CharField(max_length=2, default='CA', blank=True, null=True, verbose_name='State')
postal = models.CharField(max_length=5, blank=True, null=True, verbose_name='Postal Code')
def __str__(self):
return '{}'.format(self.person.current_identity)
class Meta:
db_table = 'Contact'
verbose_name = 'Contact'
verbose_name_plural = 'Contacts'
class Department(models.Model):
department_id = models.CharField(max_length=5, blank=False, null=False, verbose_name='Department ID')
description = models.CharField(max_length=255, blank=False, null=False, verbose_name='Department Description')
def __str__(self):
return '{}'.format(self.description)
class Meta:
db_table = 'Department'
verbose_name = 'Department'
verbose_name_plural = 'Departments'
class Job(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, verbose_name='Name')
code = models.CharField(max_length=255, blank=False, null=False, verbose_name='Code')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'Job'
verbose_name = 'Job'
verbose_name_plural = 'Jobs'
class JobPosition(models.Model):
job = models.ForeignKey(Job, blank=True, null=True, verbose_name='Job')
reports_to = models.ForeignKey('JobPosition', blank=True, null=True, verbose_name='Reports To')
name = models.CharField(max_length=255, blank=True, null=True, verbose_name='Name')
number = models.CharField(max_length=255, blank=False, null=False, verbose_name='Number')
def __str__(self):
return '{}'.format(self.name)
class Meta:
db_table = 'JobPosition'
verbose_name = 'Job Position'
verbose_name_plural = 'Job Positions'
class JobAssignment(models.Model):
person = models.ForeignKey(Person, blank=False, null=False, verbose_name='Person')
position = models.ForeignKey(JobPosition, blank=False, null=False, verbose_name='Position')
location = models.ForeignKey(Location, blank=True, null=True, verbose_name='School')
classification = models.ForeignKey(Classification, blank=True, null=True, verbose_name='Classification')
start_date = models.DateField(blank=True, null=True, verbose_name='Start Date')
end_date = models.DateField(blank=True, null=True, verbose_name='End Date')
effective_date = models.DateField(blank=True, null=True, verbose_name='Effective Date')
fte = models.CharField(max_length=10, blank=True, null=True, verbose_name='FTE')
seniority_date = models.DateField(blank=True, null=True, verbose_name='Seniority Date')
last_start_date = models.DateField(blank=True, null=True, verbose_name='Last Start Date')
last_pay_date = models.DateField(blank=True, null=True, verbose_name='Last Pay Date')
entry_date = models.DateField(blank=True, null=True, verbose_name='Position Entry Date')
record_number = models.IntegerField(default=0, verbose_name='Position Record Number')
pay_group = models.CharField(max_length=3, blank=True, null=True, verbose_name='Pay Group')
indicator = models.CharField(max_length=1, blank=True, null=True, verbose_name='Indicator')
full_or_part_time = models.CharField(max_length=1, blank=True, null=True, verbose_name='Full/Part')
standard_hours_per_week = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, verbose_name='Standard Hours per Week')
pay_status = models.CharField(max_length=1, blank=True, null=True, verbose_name='Pay Status')
comp_rate = models.DecimalField(max_digits=15, decimal_places=6, blank=True, null=True, verbose_name='Comp Rate')
comp_frequency = models.CharField(max_length=10, blank=True, null=True, verbose_name='Comp Freq')
hourly_rate = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name='Hrly Rate')
daily_rate = models.DecimalField(max_digits=10, decimal_places=6, blank=True, null=True, verbose_name='Daily Rt')
rate_code = models.CharField(max_length=10, blank=True, null=True, verbose_name='Rate Code')
compensation_rate = models.DecimalField(max_digits=15, decimal_places=6, blank=True, null=True, verbose_name='Compensation Rate')
total_cdays = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, verbose_name='TOTAL_CDAYS')
teacher_hours = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True, verbose_name='Teacher Hours')
def __str__(self):
return '{} - {}'.format(self.position.name, self.position.number)
#classmethod
def current_assignments(cls):
return cls.objects.filter(Q(end_date__gte=timezone.now()) | Q(end_date=None)).exclude(person__ssn__isnull=True).exclude(person__current_identity__isnull=True).exclude(person__contact__isnull=True)
class Meta:
db_table = 'JobAssignment'
verbose_name = 'Job Assignment'
verbose_name_plural = 'Job Assignments'
ordering = ['location__name', 'person__current_identity__last_name', 'person__current_identity__first_name', 'position__name']