Python Django always passes id 1 on ForeignKey with to_field

Viewed 30

I'm new to Django and trying to create a small application that shows scanned data from virtual machines that are inserted in a table named HostsFixDataScans.

To access the scanned data in HostsFixDataScans via the Hosts model, I defined a ForeignKey with to_field.

But unfortunately, the data returned by the linked HostsFixDataScans are wrong.

I checked the SQL statements and when requesting the HostsFixDataScans table, not the id of the Host is used, but always 1.

My domain = models.ForeignKey(Domains, on_delete=models.CASCADE) definition which does not use to_field works correctly.

I'm pretty sure, I have a misunderstanding of the definition of this relationship.

Maybe you could give me some hints how to solve the problem? Many thanks in advance!

Here are the shortened definitions of the models:

class Os(models.Model):
    operatingsystem = models.CharField(max_length=32)
    lsbdistcodename = models.CharField(max_length=32)
    lsbdistrelease = models.CharField(max_length=32, db_collation='ascii_bin')
    lsbmajdistrelease = models.IntegerField()
    remarks = models.CharField(max_length=256, blank=True, null=True)

class HostsFixDataScans(models.Model):
    host_id = models.PositiveIntegerField(primary_key=True, unique=True)
    scan_id = models.PositiveIntegerField()
    os = models.ForeignKey(Os, on_delete=models.CASCADE)

class Hosts(models.Model):
    hostname = models.CharField(max_length=256)
    domain = models.ForeignKey(Domains, on_delete=models.CASCADE)
    is_virtual = models.PositiveIntegerField(blank=True, null=True)
    os = models.ForeignKey(HostsFixDataScans, to_field='host_id', on_delete=models.CASCADE)
1 Answers

Sorry folks,

I made a really stupid mistake by connecting the field os_id with the field host_id on the other table.

I now added a field last_fix_data_scan_id to the Hosts table which has to be filled with every scan of a machine now. But doing it this way I can now request the Hosts by connecting this new field with the scan_id of HostsFixDataScans.

Related