0

I am trying to create a model to represent travel time between two venues, so it has two foreign keys to the Venue model:

class VenueTravel(models.Model):
    venue1 = models.ForeignKey('Venue', related_name='travel_times')
    venue2 = models.ForeignKey('Venue', related_name='travel_times')
    minutes = models.IntegerField(default=0, validators=[MinValueValidator(0)])

    class Meta:
        unique_together = ('venue1', 'venue2')

However, I'm having trouble making the migration for this model because the related name clashes for both fields. Usually, I would understand why, but since in this case the related object relation back to this object represents the same for both fields (all travel distances for the venue, no matter if it's venue1 of venue2), I don't really care about naming them differently. In fact, I'd want to name them the same.

Is there any way I could do that?

If you think there's a better way of modelling this use case, please feel free to make your suggestion.

dabadaba
  • 9,064
  • 21
  • 85
  • 155

1 Answers1

2

I suppose such behavior is to resolve the ambiguity because the value of related_name will be used so that the foreign-key model (here is Venue) would have access to each model (here is only VenueTravel) that has been related to it via each related field, thus the ambiguity as more than 1 field has the same name (even though as you pointed out, they just refer to the same model).

You could choose to have just different related names:

venue1 = models.ForeignKey('Venue', related_name='from_travel_times')
venue2 = models.ForeignKey('Venue', related_name='to_travel_times')

One use case for such need of distinction is as documented here:

More than one foreign key to the same model¶

If your model contains more than one foreign key to the same model, you’ll need to resolve the ambiguity manually using fk_name. For example, consider the following model

class Friendship(models.Model):
    from_friend = models.ForeignKey(
        Friend,
        on_delete=models.CASCADE,
        related_name='from_friends',
    )
    to_friend = models.ForeignKey(
        Friend,
        on_delete=models.CASCADE,
        related_name='friends',
    )
    length_in_months = models.IntegerField()

Here is another documentation stating how to work with such kind of situations:

Working with a model with two or more foreign keys to the same parent model¶

It is sometimes possible to have more than one foreign key to the same model. Take this model for instance:

from django.db import models

class Friendship(models.Model):
    to_person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="friends")
    from_person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="from_friends")

Related questions resolved by different values for the related_name: