Reputation: 1509
In Django,
Say I have two classes, A and B.
B is the child of A. I want there to be an integer field in B that is the pk of A. I want this field in B to be initialized as such whenever I create a B object.
Thanks.
p.s. essentially I want to be able to access the pk of the parent object from the child class. If there is an easier/better way, please advise
Upvotes: 0
Views: 767
Reputation: 34553
If you're leveraging a ModelForm to create the instance of B
, you can pass in the instance of A
to your form and set the value there. This way you don't have to set it in the view code.
You'll also want to exclude the a
field from the B_Form
class B_Form(forms.ModelForm):
class Meta():
exclude = ('a',)
def __init__(self, *args, **kwargs):
self.a = kwargs.pop('a')
super(B_Form, self).__init__(*args, **kwargs)
def save(self, force_insert=False, force_update=False, commit=True):
instance = super(B_Form, self).save(commit=False)
instance.a = self.a
if commit:
instance.save()
return instance
and to leverage this form class in a view:
from your_app.forms import B_Form
def your_view(request, a_pk):
a = get_object_or_404(A, pk=a_pk)
b_form = B_Form(request.POST or None, a=a)
if request.method == 'POST' and b_form.is_valid():
b_form.save()
return render('your-template.html', {'b_form': b_form})
Upvotes: 0
Reputation: 272
you need to set up class A as a foreign key to class B
class B(models.Model):
a = models.ForeignKey(A)
...
new b = B.objects.create(a=instance_of_class_a, ...)
Upvotes: 3