Search code examples
djangodjango-modelsdjango-templatesforeign-keysjinja2

how travel between models having same foreign key sql


how can I travel dynamically between modals which have same foreign key ?

say i have witers and their posts and their details tables post and detail table have a fk to writer now my question is can i travel from post to fk writer and then from fk writer to detail table dynamically

{{post.writer.detail}

is there something of this sort which can be implemented in html


Solution

  • One way to go about this is to add a property method to model class and access it on your template.

    For ex:

    class Writer(models.Model):
        # some properties
        
        @property
        def get_detail(self):
            # if detail objects does not exist it throws an error
            return Detail.objects.get(writer__id=self.id) 
         
    
    class Detail(models.Model):
        writer = models.ForeignKey(Writer,...)
        # some properties
    
    class Post(models.Model):
        writer = models.ForeignKey(Writer,...)
        # some properties
        
    

    in your template {{post.writer.get_detail}}

    The second method : If your FK is unique in detail table , you can also use reverse lookup on your template like this {{post.writer.detail_set.0}}

    In case of FK is unique, consider using OneToOneField and you can access detail {{post.writer.detail}}