[Answered ]-Django table – replace ID with two primary keys (or something similar)

1👍

You can work with a UniqueConstraint [Django-doc] for a uniqness constraint (that can span over multiple columns).

This then looks like:

from django.conf import settings
from django.db import models


class MyModel(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    data = models.CharField(max_length=32)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=('user', 'data'), name='unique_data_per_user'
            )
        ]

is there any way I can nix the auto-generated id column? It takes up a lot of space.

No, this has been requested multiple times, but has been rejected every time. The reason is likely not that much the database; but also how to refer to objects in the URL path and <select> widgets, as well as the fact that a lof of Django’s "ecosystem" has been built with the assumption that the primary key refers to a single unique field.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Leave a comment