Hi I am simply trying to create an object for Table2 with a foreign key to Table1.
Here are my models:
class Table1(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField() class Meta: managed = False db_table = 'table1' class Table2(models.Model): id = models.IntegerField(primary_key=True) date = models.DateField() home_team = models.ForeignKey('Table1', models.DO_NOTHING, blank=True, null=True) away_team = models.ForeignKey('Table1', models.DO_NOTHING, related_name='games_away_team_set', blank=True, null=True) class Meta: managed = False db_table = 'table2'
The foreign key fields are clearly defined but when I try to create a new table2 object, I can’t seem to access the field. For example, I have a data migration file that uses RunPython() to populate my database using a JSON file, with predefined keys. Here is the relevant code:
(Games is the table2 object)
with open(games_json_path, 'r') as f: games = json.load(f) for game in games: #Create a game g = Games.objects.create(id=game['id'], date=game['date'], home_team=game['homeTeam']['id'], away_team=game['awayTeam']['id']) g.save()
Here, I try to use the pk for the table1 object, directly from the JSON data. However, even if I try to look up the instance and define the foreign key that way, I still get the same error when trying to run this migration.
Here is the error: “TypeError: Games() got unexpected keyword arguments: ‘home_team’, ‘away_team’”
I’ve gone into the shell and made sure my Game has the correct fields:
Get the list of field names in the Games model ...: field_names = [field.name for field in Games._meta.fields] ...: print(field_names)
which outputs: [‘id’, ‘date’, ‘home_team’, ‘away_team’]
No matter what I do, I can’t seem to access these fields and correctly create a Game object.
Any help would be much appreciated.