Jamison
Jamison

Reputation: 21

Django model references from a different model

I'm writing a method in a model and I need to access an attribute from another model.

from django.db import models

class Image(models.Model):
    name = models.CharField(max_length=30)
    image = models.ImageField(upload_to = slug_path)


    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

    def slug_path(self):
        # Need Article.slug from Article class here for constructing path
        pass

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
    slug     = models.SlugField(max_length=50)

    def __str__(self):              
        return self.headline

I want to write a method in the Image class that will have access to the slug of the Article it is included in via the one to many relation. Is this possible or is there a different way I should be going about this entirely?

Upvotes: 1

Views: 65

Answers (2)

daveclever
daveclever

Reputation: 58

Add a relationship to Image corresponding to the Article object, like you did with Article and Reporter.

article = models.ForeignKey(Article, on_delete=models.CASCADE)

Then to get/return the slug:

def slug_path(self):
    return self.article.slug

Upvotes: 0

sprksh
sprksh

Reputation: 2384

Say if only one image can be related to one article, you need to add a field article in the image model which would be foreign key to Article model

article = models.ForeignKey(Article)

Now,

def slug_path(self):
        slug = self.article.slug
        return slug

Anyway, you can do it in a similar way for many to many fields etc.

Upvotes: 1

Related Questions