1

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?

5
  • 2
    Based on your design, one schedule can have multiple events right? So which event's long_name you intend to return? I am saying this because you are approaching it in a wrong way Commented Jan 25, 2017 at 10:09
  • of course... It needs to be a one to one relationship then? Commented Jan 25, 2017 at 10:10
  • 1
    One more question an Event needs to have a schedule right? If yes, change your models Commented Jan 25, 2017 at 10:11
  • The very underlying assumptions are not clear to you. Your intent when defining the str method means that a schedule can only be related to one single event but you are using foreign key which is a one -to-many relationship. Commented Jan 25, 2017 at 10:13
  • I want Events to be able to have more than one schedule, but Schedules should only be linked to one event. Commented Jan 25, 2017 at 10:30

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

This is of course correct, but the language is the reverse of what the models do which confuses me sometimes. Events don't have schedules at all - schedules have foreign keys to events - which is the reverse.

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.