On 7/02/2013 5:04pm, Derek wrote:
I am trying to access the field(s) of a Child table while still inside
the save method of the Parent table.
Assuming that the many-to-many field in the Parent table is called
`m2m_field`, and the field I need to access in the Child table is
called `child_field`, what I have tried is this:
What I think you need in the Parent model is access to the "through"
table - say Parent_Child - which has a foreign key to both Parent and
Child called Parent_Child.parent and Parent_Child.child respectively.
Like this ...
class Parent(models.Model):
child = models.ManyToManyField('Child', through='Parent_Child')
#
..
def save(self, *args, **kwargs):
obj_qs = Parent_Child.objects.filter(parent=self)
# which gives you a query set to play with and extract obj
# or if you know the child object
# obj = Parent_Child.objects.get(parent=self, child=whatever)
# which gives you obj
# then ...
data_I_need = obj.thingummy
super(Parent, self).save(*args, **kwargs)
This is not necessarily the correct way to do things. I think there
might be Django shortcut but I'm not immediately familiar with it. I'd
have to read the query docs.
Mike
def save_model(self, request, obj, form, change):
# save object and the many-to-many data
obj.save()
# this does not work:
data_I_need = obj.m2m.all()[0].child_field
# nor does this:
data_I_need = Parent.objects.get(pk=obj.pk).m2m.all()[0].child_field
# in fact, length is 0, so no data in the set...
print len(Parent.objects.get(pk=obj.pk).m2m.all())
I know I am not grasping some key aspect of the problem; but I cannot
see what it is, and would appreciate any help with this problem!
Thanks
Derek
--
You received this message because you are subscribed to the Google Groups "Django
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.