Search code examples
djangodjango-users

Making use of the users table, causing an error


In Django (2.x) I have an entry form, the model is here:

from django.db import models
from django.contrib.auth.models import User
from django.conf import settings

class Sample(models.Model):
    sample_id = models.AutoField(primary_key=True)
    area_easting = models.IntegerField()
    area_northing = models.IntegerField()
    context_number = models.IntegerField()
    sample_number = models.IntegerField()
    # taken_by = models.IntegerField()
    taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.PROTECT)

    def __str__(self):
        return str(self.sample_id)

    class Meta:
        db_table = 'samples\".\"sample'
        #ordering = ["sample_id"]
        managed = False
        #verbose_name_plural = "samples"

This works as expected, a list of usernames drops down (while I would like to format - firstname lastname). However, when I return to the main viewing page I see an error.

django.db.utils.ProgrammingError: column sample.taken_by_id does not exist
LINE 1: ...text_number", "samples"."sample"."sample_number", "samples"....
                                                             ^
HINT:  Perhaps you meant to reference the column "sample.taken_by".

Clearly Django is adding the _id to the table name causing the error, I expect because it is a foreign key.

Any ideas how to remedy this behaviour?


Solution

  • You can explicitly set the underlying db column via the db_column attribute:

    taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='taken_by', on_delete=models.PROTECT)