djangodjango-modelsdjango-rest-frameworkdjango-extensions

Timestamped model __init__() got multiple values for argument 'on_delete'


I'm trying to create a foreignkey relationship in DRF models with an on_delete

fk_city = models.ForeignKey("region_mgmt.City", "warehouses", on_delete=models.SET_NULL)    
TypeError: __init__() got multiple values for argument 'on_delete'

below is my code:

from django_extensions.db.models import TimeStampedModel

class State(TimeStampedModel, models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True)
    name = models.CharField(max_length=100)
    postal_code = models.CharField(max_length=20, blank=True, null=True)
    fk_country = models.ForeignKey(Country, related_name="states", on_delete=models.CASCADE)

    def __str__(self):
        return self.name
class City(TimeStampedModel, models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True)
    name = models.CharField(max_length=100)
    postal_code = models.CharField(max_length=20, blank=True, null=True)
    fk_state = models.ForeignKey(State, related_name="cities", on_delete=models.CASCADE)

    def __str__(self):
        return self.name

and in another module I have the following model

class Warehouse(TimeStampedModel, models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True)
    name = models.CharField(max_length=255, null=False, blank=False)
    address = models.TextField(null=False, blank=False)
    fk_city = models.ForeignKey("region_mgmt.City", "warehouses", on_delete=models.SET_NULL)
    contact_no = models.CharField(max_length=100)

does anyone know the reason and its solution?


Solution

  • The second parameter of a ForeignKey is the on_delete=… parameter [Django-doc], so you specify two values for this. Likely you want to use your warehouses as related_name=… parameter [Django-doc], so you implement this as:

    class Warehouse(TimeStampedModel, models.Model):
        # …
        fk_city = models.ForeignKey(
            'region_mgmt.City',
            related_name='warehouses',
            on_delete=models.SET_NULL,
            null=True
        )