Xeberdee
Xeberdee

Reputation: 2057

Django - Return foreignkey field in string method

I want to return a foreign key field value as the unicode or string method of another model.. like this..

class Schedule(models.Model):
    month = models.charField(max_length=20)
    .... lots more fields here

    def __str__(self):
        return related_model.Event.long_name

class Event(models.Model):
    schedule = models.Foreignkey(Schedule)
    long_name = models.CharField(max_length=100)

I'm not sure how to do it, because if the order of the classes is reversed then Event can't have a foreign key to Schedule.

What would be the correct way to do this kind of thing?

Upvotes: 1

Views: 7418

Answers (1)

Rajesh Yogeshwar
Rajesh Yogeshwar

Reputation: 2179

My understanding is that an event can have multiple schedules, which might be possibly what you want. If that is the case, change your models to this

class Event(models.Model):
    long_name = somefield


class Schedule(models.Model):
    event = models.ForeignKey(Event)

    def __str__(self):
        return self.event.long_name

Upvotes: 1

Related Questions