How to use select_related with Django create()?

Viewed 232
class Parent(models.Model):
    # some fields

class Child(models.Model):
    parent = models.ForeginKey(Parent)
    species = models.ForeignKey(Species)
    # other fields

I have a function like this:

1. def some_function(unique_id):
2.     parent_object = Parent.objects.get(unique_id=unique_id)
3.     new_child = Child.objects.create(name='Joe', parent=parent_object)
4.     call_some_func(new_child.parent.name, new_child.species.name)

In the line 4, a db query is generated for Species. Is there any way, I can use select_related to prefetch the Species, so as to prevent extra query.

Can it be done while I use .create(). This is just an example , I am using many other fields too and they are querying the DB every time.

The only way I can think is after line 3 using this code:

child_obj = Child.objects.select_related('species').get(id=new_child.id)
0 Answers
Related