1

I have this project where, I need to fetch multiple objects from multiple models in a view. I could do that by for loop but I think I shouldn't hit database in each loop. Should I use prefetch_related. or Should I know some other way to retrieve them.

for example:

class A(models.Model):
     title_name=models.CharField(...)
     id=models.AutoField(pk=True)

class B(models.Model):
     user=models.ForeignKey(User,models.ON_CASCADE=True)
     user_status=models.CharField(...)
     id=models.ForeignKey(A, models.ON_CASCADE=True)

I need to display user_status, user and associated title_name. I get multiple objects, select_related will not be useful. Any suggestions.

8
  • try to use property Commented Jun 22, 2017 at 5:49
  • 1
    Yes, you should use prefetch_related. There is no better way than that Commented Jun 22, 2017 at 5:57
  • @Gahan could you please tell me how to use property Commented Jun 22, 2017 at 6:04
  • @SardorbekImomaliev I have tried prefetch_related , i couldn't exactly do what i wanted to, I've made a query something like B.objects.get(user=request.user).prefetch_related('id') Commented Jun 22, 2017 at 6:07
  • see this one: stackoverflow.com/questions/3046398/… you can implement function in class which you want to call in view and in property you can use function to fetch related values to your model Commented Jun 22, 2017 at 6:08

1 Answer 1

1

You need make this queryset:

B.objects.all().select_related('user', 'id')

This queryset will generate sql that join user and A data from db

Next, in the model B to make a property:

@property
def title_name(self):
    return self.id.title_name

Finally you'll get queryset that makes one SQL request to database and returns all data you need.

By the way, I would rename attribute "id" in the model B to "a".

Sign up to request clarification or add additional context in comments.

3 Comments

I would like to filter B objects, all() method could be costly.
@joelvarma select_related method in this case will work because id is foreign key. If you were to filter A model so you would need to use prefetch_related
Yea, i want to filter A, so how should i use prefetch_related

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.