我试图使用bulk_create,这样我就可以保存到数据库,但我写的代码只能保存一个数据,但当我想保存多个数据时,它给了我这个错误“NoneType对象没有属性'pk'”
我试过这个,我的期望是保存所有的股份一次根据成员的人数
def new_share(request):
success_count = 0
group = GroupMember.objects.filter(user=request.user).first()
attendance = Attendance.objects.filter(group=group,meeting__date=date.today())
config = ConfigurationData.objects.filter(group=group).first()
members = Member.objects.filter(group=group, is_active=True)
for member in members:
member.created_at = member.created_at.strftime('%Y-%m-%d')
members_json = json.dumps(list(members.values()),default=str)
attendance_data = [
{'member_id': data.member.id, 'attended': data.attended}
for data in attendance
]
if not attendance:
messages.warning(request,f'Please make sure you have take an attendance for this meeting before you buy a share.')
if request.method == 'POST':
member_ids = [key.split('_')[-1] for key in request.POST.keys() if key.startswith('amount_of_share_')]
print(member_ids)
instances = []
for member_id in member_ids:
member = get_object_or_404(Member,group=group,id=int(member_id))
amount_key = 'amount_of_share_'+ member_id
amount = int(request.POST.get(amount_key,0))
print(f'amount is {amount} and for member {member}')
if amount > 0:
try:
instances.append(ShareManagement.buyshare(request,value=amount,member=member.id))
success_count +=1
except Exception as e:
messages.error(request,f"Error processing data for {member.memberID}: {str(e)}")
print(f'Error processing data for {member.memberID}: {str(e)}')
else:
print(f'Process the fine for not buying a share for member {member.memberID}')
print(instances)
Share.objects.bulk_create(instances)
if success_count > 0:
messages.success(request,f'{success_count} shares have been successfully saved.')
return redirect('app:share')
context = {
'attendance':json.dumps(attendance_data),
'config':config,
'members_json':members_json,
'members':members
}
return render(request,'shares/add_share.html',context)
字符串
1条答案
按热度按时间dgjrabp21#
ShareManagement.buyshare(request,value=amount,member=member.id)
是什么?instances 必须是bulk_create工作的模型示例列表。应该是这样的字符串
但是你把这个buyshare方法的结果附加到你的列表上