How to pass an object to a model field in Django?
I am trying to pass an object I get from a model form to a field in a model.
Three models are involved here. Patient , Donation and Donor
Here are the models:
class Donor(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
donor_dob = models.DateField(auto_now=False, auto_now_add=False, default=None)
id_card = models.CharField(max_length=7)
phone_number = models.CharField(max_length=7)
blood_group = models.CharField(max_length=20, choices=BLOOD_GROUPS, default='O_Positive')
availability = models.BooleanField(default=True)
donor_donation = models.ForeignKey(
'Donation', blank=True, null=True, on_delete=models.DO_NOTHING)
class Patient(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=30)
patient_dob = models.DateField(auto_now=False, auto_now_add=False, default=None)
id_card = models.CharField(max_length=7)
phone_number = models.CharField(max_length=7)
blood_group = models.CharField(max_length=20, choices=BLOOD_GROUPS, default='O+')
class Donation(models.Model):
donation_donor = models.ForeignKey(
Donor, on_delete=models.CASCADE, related_name='donations')
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
donation_date = models.DateTimeField(auto_now=True)
amount = models.DecimalField(max_digits=5, decimal_places=2)
I am using DonationForm to enter a new donation record.
here is the form:
class DonationForm(forms.ModelForm):
donation_donor = forms.ModelChoiceField(
queryset=Donor.objects.filter(availability=True))
class Meta:
model = Donation
fields = ['donation_donor', 'patient', 'amount']
and finally here is the view for entering a new donation object/record
def new_donation(request):
if request.method == 'POST':
form = DonationForm(request.POST or None)
# print(request.POST)
print(request.POST['donation_donor'])
if form.is_valid():
donor = Donor.objects.get(id=request.POST['donation_donor'])
donor.availability = False
print('Donor: ', donor)
donation = form.save()
form.save()
donor.donation_donor = donation
donor.save()
donor = setattr(donor, 'donation_donor', donation)
print(donor)
return render(request, 'new_donation.html', {'form': form})
form = DonationForm()
return render(request, 'new_donation.html', {'form': form})
WHAT I AM TRYING TO DO
When I get a donation object from the form.save() I assign that object into the `donation' variable here and I want to assign/pass that object to the donor_donation field in the Donor model which is a ForeignKey to Donation model.
I thought I would be able to change that field just like how I set the availability of Donor to False here but it did not work. How should I approach to get around this?