Multipe one-to-many relation between two models

I am stuck on a question that I really need help in so I was creating a route finder and I have created a model of the vehicle with 2 relations start_location and final_location. I want them to be foreign keys as I don't want to have multiple options when selecting start and final location and foreign key defines one-to-many relation that means one location can have multiple vehicle but one vehicle can't be related to multiple location.

So my question is will Django Give me error if I create multiple foreign key fields and connect to location that I think (I may be wrong) will create many-to-many relation

Thank you for your insight

class Destination(models.Model):
    name = models.CharField(max_length=100)
    state = models.ForeignKey(State, on_delete=models.CASCADE,related_name="destination")
    country = models.ForeignKey(Country, on_delete=models.CASCADE,related_name="destination")


class vehicle(models.Model):
    start_time = models.CharField(max_length=10)
    reaching_time = models.CharField(max_length=10)
    startdestination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name="startdestinations")
    subdestination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name="subdestinations")
    finaldestination = models.ForeignKey(Destination, on_delete=models.CASCADE,related_name="finaldestinations")
    fare = models.IntegerField()
    confirmed = models.BooleanField()
    distance = models.IntegerField()

Will Django give me an error if I create multiple foreign key fields and connect to location?

No, given the related_name=… [Django-doc] and the related_query_name=… [Django-doc] are unique. Sicne the related_query_name=… defaults to the related_name=… if given, it is thus sufficient to provide a unique related_name=… and not construct ForeignKeys with a given equivalent related_query_name=….


Note: The related_name=… parameter [Django-doc] is the name of the relation in reverse, so from the Destination model to the Vehicle model in this case. Therefore it (often) makes not much sense to name it the same as the forward relation. You thus might want to consider renaming the startdestination relation to vehicles_started.

Вернуться на верх