Home > other >  Relate one model field to another model field twice Django
Relate one model field to another model field twice Django

Time:11-08

I am making an inventory system, and one thing I would like to be able to track is transfers. I have two models

class Location(models.Model):
    class FacilityChoices(models.TextChoices):
        warehouse = 'Warehouse'
        location = 'Location'

    name = models.CharField(max_length=255, null=False, blank=False)
    street_ad = models.CharField(max_length=128, verbose_name='Street address')
    city_ad = models.CharField(max_length=128, verbose_name='City Address')
    state_prov = models.CharField(max_length=30, verbose_name='State/Province')
    country = models.CharField(max_length=50, verbose_name='Country')
    zip_code = models.CharField(max_length=20, verbose_name='Zip/Postal code')
    facility_type = models.CharField(max_length=30, choices=FacilityChoices.choices, default=FacilityChoices.warehouse)

...


class Transfer(models.Model):
    item = models.ForeignKey(Stock, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    location_send = models.ForeignKey(Location, on_delete=models.CASCADE)
    location_receive = models.ForeignKey(Location, on_delete=models.CASCADE)

but I receive an error (fields.E304) when I do this. What would be the best way to accomplish this?

CodePudding user response:

By creating this foreign key relationship there will be a reverse lookup from location to transfer, by default is named "location.transfer_set" by django. But then there are two fields with the same relationship name. To address this you will need to add a related_name param to specify the lookup name.

class Transfer(models.Model):
    item = models.ForeignKey(Stock, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    location_send = models.ForeignKey(Location, related_name="transfer_send", on_delete=models.CASCADE)
    location_receive = models.ForeignKey(Location, related_name="transfer_receive", on_delete=models.CASCADE)

To disable this backward relationship you could set related_name as " " or end it with " "

  • Related