Hello, I have a problem and will be very happy if someone can help. I have a the following model
class Post(models.Model):
...
title = models.CharField(max_length=500)
related_to=models.ForeignKey(Related, related_name='post',
on_delete=models.CASCADE,blank=True,null=True)
...
where related_to connected with
class Related(models.Model):
book = models.OneToOneField(Book, related_name='related',null=True, blank=True,
on_delete=models.CASCADE)
novel = models.OneToOneField(Novel,related_name='related', null=True, blank=True,
on_delete=models.CASCADE)
def __str__(self):
if self.book:
return self.book.title.original_name
elif self.novel:
return self.novel.title.original_name
else:
return 'None'
The Book and Novel models are associated with the Title model, which has an original_name field. Also I have the following form to edit the fields I need
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'main_image', 'related_to']
My problem is that when i create a form like below, every time i make redundant sql queries because of my __str__
method and every time i get full list of fields of Book
/Novel
models and also additional sql query to Title
model,which is definitely redundant when I only need the name
My problem is that I need to get from my Book/Rovel models only the id and original_name field from the related Title model, but I don’t know how to access only those fields in my form.
I thought about something like this ‘related_to__book__title__original_name’ to avoid sql query to title model, but it doesnt work.