Bug or unaccepted behaviour

29 views
Skip to first unread message

Arink Verma

unread,
Feb 14, 2016, 7:06:43 AM2/14/16
to Django users
Hi Django Experts

I came across something unaccepted while using signal. 


    def clone_creatives(self, src_theme_id):
        themeA = Theme.objects.get(id=src_theme_id)
        self.unit_set.all().delete()
        for u in themeA.unit_set.all():
            u.id = None
            u.theme_id = self.id
            u.save()


@receiver(post_save, sender=Unit)
def unit_post_save(sender, instance, **kwargs):
    print instance.theme.id

 Here instead of printing id of self theme it is still showing id of themeA. 
But if is use
u.theme = self
everything work normal.

What's the different between u.theme = self and u.theme = self.id ?

Andreas Kuhne

unread,
Feb 14, 2016, 9:38:25 AM2/14/16
to django...@googlegroups.com
Hi, 

Would need to see more of you code to understand exactly what you want to do.

Regarding your question. It doesn't make sense, but I think you are asking the difference between "u.theme_id = self.id" and "u.theme = self"? I don't know exactly the difference, but I do know that you shouldn't handle the foreignkey references yourself. You SHOULD use "u.theme = self", and I think the reason for this is that the save method changes the u.theme_id via the u.theme object.

I always handle the foreign keys with the objects rather then the id's.

Regards,

Andréas

--
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...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/aceb013e-6471-4407-b5c4-746cefca62c1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

James Schneider

unread,
Feb 14, 2016, 2:57:05 PM2/14/16
to django...@googlegroups.com

>>>     def clone_creatives(self, src_theme_id):
>>>         themeA = Theme.objects.get(id=src_theme_id)
>>>         self.unit_set.all().delete()
>>>         for u in themeA.unit_set.all():
>>>             u.id = None
>>>             u.theme_id = self.id

This line is your problem. You can use foo_id fields as getter properties if you don't want to trigger the FK look-up, but I don't believe they work as setters. Instead use:
u.theme = self.id

If you specify the integer (or more accurately, the raw PK value of the related object) on an FK field, Django will use that value.

Honestly, though, doing that doesn't save you anything and makes your code more complex to figure out, since you already have a fully populated Theme object in self available in this case.

-James

Reply all
Reply to author
Forward
0 new messages