0

I'm trying to create a order model that is referencing the non primary-key field rfid of my user model. In order to do that I'm using a foreign-key relationship using the attribute to_field.

My user model is inheriting from AbstractUser and I added the rfid field with unique=True that is necessary for the to_field attribute:

class CustomUser(AbstractUser):
    rfid = models.IntegerField(unique=True, null=True, blank=True)

Following the order model:

class Order(models.Model):
    rfid = models.ForeignKey('CustomUser', on_delete=models.CASCADE, to_field="rfid")
    coffee = models.ForeignKey('Coffee', on_delete=models.DO_NOTHING)
    amount = models.IntegerField(null=True, blank=True)
    datetime = models.DateTimeField()

Having a look in the django-admin there still are the usernames listed for the rfid reference instead of the actual rfid entries that are made in the database. I attatched a picture on Imgur as I haven't got he reputation yet to post images on here.

Why is that? I studied other posts but couldn't figure it out.

Ralf
  • 16,086
  • 4
  • 44
  • 68
alexanderdavide
  • 1,487
  • 3
  • 14
  • 22
  • Your picture doesn't show anything at all relevant to `to_field`. It just shows the default string representation of the linked models. Are you actually sure you understand what `to_field` does, and that you need to set to_field at all? – Daniel Roseman Aug 13 '18 at 21:12
  • To my understanding the to_field attribute allows to reference a different field than the default primary-key field referenced by django. The picture clearly shows that the field 'rfid' still contains the username attribute instead of the referenced rfid field (to_field="rfid"). If I understand it wrong please enlighten me or maybe there is a different method how I can reference the rfid field to my order model. – alexanderdavide Aug 14 '18 at 06:52
  • 1
    No, the picture shows the *representation* of the linked model, which is determined by its `__str__` method. You can change that by overriding the form class and redefining the relevant field, if you want to. There is rarely any reason to change the to_field, as the fk itself gives you access to the whole linked model. – Daniel Roseman Aug 14 '18 at 07:38

0 Answers0