I have two classes, one called phase1
and one called phase2
. phase2
has an instance of phase1
in it (as a Foreign Key relationship). Now I want to make another class, called POObject
, that has a Foreign Key value called purchase
to either a phase1
or a phase2
object. That is, I want to be able to create a POObject
with purchase
set to a phase1
instance, and then later change it to a phase2
instance.
I believe this is called Duck Typing, but I'm not sure if there's an easy way to do it in Django. I know Python allows for Duck Typing quite easily, but I'm guessing the Database won't allow it without at least some additional work.
Any advice on how do to this would be much appreciated.
After implementing orlenko's suggestion, I'm having trouble adding new items. Here are the views that deal with creating a new instance. The way it works is by creating a new purchase
in new
, and then using the instance of that purchase
in new2
to create a POObject
.
def new(request):
if request.method == 'POST':
form = PurchaseOrderForm(request.POST)
if form.is_valid():
new_po = form.save()
return HttpResponseRedirect('/workflow/%s' %new_po.request_number)
else:
return render(request, 'input.html', {'input_type': 'Purchase Order','formset': form, 'error': True})
else:
form = PurchaseOrderForm()
return render(request, 'input.html', {'input_type': 'Purchase Order','formset': form,})
def new2(request, number):
po=PurchaseOrder.objects.get(pk=number)
if request.method == 'POST':
form = WorkflowForm(request.POST, initial={'purchase': PurchaseOrder.objects.get(pk=number), 'state': 'request'})
if form.is_valid():
new_flow = form.save()
return HttpResponse('Good')
else:
print form.errors
return render(request, 'new-workflow.html', {'form': form, 'purchase': po})
else:
form = WorkflowForm(initial={'purchase': PurchaseOrder.objects.get(pk=number), 'state': 'request'})
return render(request, 'new-workflow.html', {'form': form, 'purchase': po, 'type': 'New'})
The appropriate form class is:
class WorkflowForm(ModelForm):
purchase1=forms.ModelChoiceField(queryset=PurchaseOrder.objects.all(), required=False)
purchase2=forms.ModelChoiceField(queryset=Phase2.objects.all(), required=False)
details = forms.CharField(required=False)
class Meta:
model = POObject