Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: __init__() got an unexpected keyword argument 'on_delete'

I built a model:

class Channel(models.Model):
    title = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(allow_unicode=True, unique=True)
    description = models.TextField(blank=True, default='')
    description_html = models.TextField(editable=False, default='', 
blank=True)
    subscribers = models.ManyToManyField(User, 
through="ChannelMembers", on_delete=models.CASCADE,)

When I do makemigration it say :

TypeError: __init__() got an unexpected keyword argument 'on_delete'

And when a delete the on_delete it say:

TypeError: __init__() missing 1 required positional argument: 'on_delete'

What's worng?

like image 638
Majid Rajabi Avatar asked Nov 04 '18 14:11

Majid Rajabi


1 Answers

on_delete is not a valid argument on a ManyToManyField. You would need to use the on_delete argument in each of the ForeignKey fields in the through model for ChannelMembers instead.

You can see the following example how this is achievable on the Django Docs website

In your case it would look something like this:

class Channel(models.Model):
    ...
    # Don't have the on_delete parameter on this field
    subscribers = models.ManyToManyField(User, through="ChannelMembers")

# Add on_delete to both the fields in this class instead
class ChannelMembers(models.Model):
    channel = models.ForeignKey(Channel, on_delete=models.CASCADE)
    subscriber = models.ForeignKey(User, on_delete=models.CASCADE)
like image 164
Johan Avatar answered Nov 15 '22 09:11

Johan