[Answer]-Django model without primary and unique field

1👍

Don’t create a model for this. Instead, add a many-to-many relation in either the Url and Monitor model.

Django will then maintain this intermediate table for you.

0👍

You probably want to make composite primary key, but django doesn’t support it:
https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys

What you could do is to let it create id field, but also add unique constraint like this:

class MonitorForUrl(models.Model):
    url = models.ForeignKey(Url, on_delete=models.CASCADE)
    monitor = models.ForeignKey(Monitor, on_delete=models.CASCADE)

    class Meta:
        db_table = 'monitors_for_url'
        constraints = [
            models.UniqueConstraint(
                fields=['url', 'monitor']
                name='unique_url_monitor'
            )
        ]

Neither field will be unique, but combination of the fields will.

Leave a comment