这个农场管理系统是我去年为一个中型农业合作社开发的实际项目。系统采用Django作为后端框架,搭配MySQL数据库,实现了从农业生产计划到农资管理的全流程数字化。在实际部署运行半年后,显著提升了农场的管理效率——农药化肥使用记录准确率从原来的68%提升到99%,生产计划执行率提高了40%。
Django的ORM系统完美适配农场管理中的复杂数据关系。比如农药入库记录需要关联农药信息、仓库管理员和供应商等多个模型。通过Django的ManyToManyField和ForeignKey,我们可以轻松建立这些关联:
python复制class Pesticide(models.Model):
name = models.CharField(max_length=100)
specification = models.CharField(max_length=50)
toxicity_level = models.CharField(max_length=20)
class PesticideStockIn(models.Model):
pesticide = models.ForeignKey(Pesticide, on_delete=models.CASCADE)
operator = models.ForeignKey(User, on_delete=models.CASCADE)
quantity = models.IntegerField()
batch_number = models.CharField(max_length=50)
production_date = models.DateField()
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
农场管理系统的核心是处理好三类数据流:
我们采用MySQL 5.7作为数据库,主要考虑到:
重要提示:农业系统的日期字段特别重要,MySQL配置中一定要设置时区为东八区,否则农事操作记录会出现时间偏差。
农药管理是系统的核心模块之一,实现了从采购到使用的闭环跟踪:
基础信息维护:
库存管理:
python复制def stock_in(request):
if request.method == 'POST':
form = PesticideStockInForm(request.POST)
if form.is_valid():
# 原子操作:创建入库记录+更新库存
with transaction.atomic():
stock_in = form.save()
stock, created = PesticideStock.objects.get_or_create(
pesticide=stock_in.pesticide,
defaults={'quantity': stock_in.quantity}
)
if not created:
stock.quantity += stock_in.quantity
stock.save()
return redirect('pesticide:stock_list')
else:
form = PesticideStockInForm()
return render(request, 'pesticide/stock_in.html', {'form': form})
生产计划模块采用了甘特图展示方式,关键实现点:
python复制def calculate_growth_period(crop_type, planting_date):
"""根据作物类型和种植日期计算预计采收期"""
base_periods = {
'tomato': 90,
'cucumber': 70,
'pepper': 85
}
standard_period = base_periods.get(crop_type, 60)
# 考虑季节因素调整
month = planting_date.month
if month in [12, 1, 2]: # 冬季
standard_period *= 1.3
elif month in [6, 7, 8]: # 夏季
standard_period *= 0.9
return planting_date + timedelta(days=standard_period)
实现农药化肥的提前预警是个挑战,我们最终方案是:
sql复制CREATE INDEX idx_pesticide_expiry ON pesticide_stock(expiry_date);
python复制@app.task
def check_expiry():
soon = date.today() + timedelta(days=30)
expiring = PesticideStock.objects.filter(
expiry_date__lte=soon,
expiry_notified=False
).select_related('pesticide')
for item in expiring:
send_notification(item)
item.expiry_notified = True
item.save()
考虑到农场工作人员常需要在田间操作,我们做了如下适配:
python复制def compress_image(image):
img = Image.open(image)
if img.mode != 'RGB':
img = img.convert('RGB')
output = BytesIO()
img.save(output, format='JPEG', quality=60)
output.seek(0)
return ContentFile(output.read(), name=image.name)
经过实际压力测试,推荐配置:
数据库查询优化:
缓存策略:
python复制class PesticideListView(ListView):
queryset = Pesticide.objects.all().select_related('supplier')
template_name = 'pesticide/list.html'
def get_queryset(self):
cache_key = 'pesticide_list'
data = cache.get(cache_key)
if not data:
data = super().get_queryset()
cache.set(cache_key, data, timeout=3600)
return data
数据录入准确性:
移动网络问题:
季节性高峰应对:
用户培训要点:
这个系统目前已在三个农场稳定运行,最大的收获是认识到农业数字化不是简单地把纸质记录电子化,而是要重构整个工作流程。比如农药管理模块,我们迭代了三次才找到最适合田间使用的操作方式。