Johnny Metz
Johnny Metz

Reputation: 5985

Django: reference relationship in fixture using unique key(s)

Let's say I have the following database models:

class Team(models.Model):
    name = models.CharField(max_length=50, unique=True)


class Player(models.Model):
    name = models.CharField(max_length=50, unique=True)
    team = models.ForeignKey(Team, on_delete=models.CASCADE)

I'm creating a fixture to load initial data into these tables, which looks like this:

# TEAMS
- model: load.team
  fields:
    id: 1
    name: Raiders

# PLAYERS
- model: load.player
  fields:
    team: 1
    name: Derek Carr
- model: load.player
  fields:
    team: 1
    name: Darren Waller

This works fine, but I'd like to reference team by its unique column name (for a more human readable file), so the player fixtures would look like this:

# PLAYERS
- model: load.player
  fields:
    team: Raiders
    name: Derek Carr
- model: load.player
  fields:
    team: Raiders
    name: Darren Waller

Is there anyway to do this, besides setting Team.name as the primary key?

Upvotes: 1

Views: 374

Answers (1)

Nico Griffioen
Nico Griffioen

Reputation: 5405

I think you can use Natural keys for this.

You should create a custom manager for Team and implement the get_by_natural_key function. You should also define a natural_key function on the Team object:

class TeamManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name=name)

class Team(models.Model):
    ...

    objects = TeamManager()

    def natural_key(self):
        return (self.name,)

Then you can use dumpdata --natural-foreign to create fixtures using the Player's natural key.

Upvotes: 1

Related Questions