0

I want to build Trip.Model, with multiple Hotel.Model assignments, each under a different field name. Example(_pb, _hv, _nl)

class Trip(models.Model):
    hotel_pb = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True)
    hotel_hv = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True)
    hotel_nl = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True)

How do I achieve this without creating multiple Hotel.Model ?

  • I have tried using the same Foreignkey, but throws error.

    Reverse accessor 'Activity.trip_set' for 'gobasic.Trip.acitivity_3' clashes with reverse accessor for 'gobasic.Trip.acitivity_1'. HINT: Add or change a related_name argument to the definition for 'gobasic.Trip.acitivity_3' or 'gobasic.Trip.acitivity_1'

zora
  • 53
  • 6
  • I am not pretty sure what was your intention but it seems to me that Many to many relation could resolve your issue: https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/ – SerSergious Nov 01 '22 at 20:25
  • 1
    @SerSergious precise fix on related_name found at: https://stackoverflow.com/questions/2606194/django-error-message-add-a-related-name-argument-to-the-definition My code fixed as such: ```class Trip(models.Model): hotel_pb = models.ForeignKey(Hotel, related_name='pb_hotel_set', on_delete=models.PROTECT, blank=True, null=True) hotel_hv = models.ForeignKey(Hotel, related_name='hv_hotel_set', on_delete=models.PROTECT, blank=True, null=True) hotel_nl = models.ForeignKey(Hotel, related_name='nl_hotel_set', on_delete=models.PROTECT, blank=True, null=True)``` – zora Nov 01 '22 at 20:32
  • Please edit your question and add this answer with correct formating, of course if it works for you. – SerSergious Nov 01 '22 at 20:33
  • I fixed the question, thanks for the suggestion. Stackoverflow won't let me answer for now :( – zora Nov 01 '22 at 20:38
  • So the code from the comment works or not? – SerSergious Nov 01 '22 at 20:47

1 Answers1

1

Use related_name, see below.

hotel_pb = models.ForeignKey(Hotel, related_name = 'hotel_pb', on_delete=models.PROTECT, blank=True)
    hotel_hv = models.ForeignKey(Hotel, related_name = 'hotel_hv',on_delete=models.PROTECT, blank=True)
    hotel_nl = models.ForeignKey(Hotel, related_name = 'hotel_nl',on_delete=models.PROTECT, blank=True)
romel rada
  • 21
  • 4