B
B
Bjornie2017-08-18 12:14:41
Django
Bjornie, 2017-08-18 12:14:41

How to check the uniqueness of data in ForeignKey fields?

This is my rather simple model with 6 fields for selecting a player in a team, so that later I can include the team in the match without adding players separately.

class Team(models.Model):
    team_name = models.CharField(max_length=255)
    t_1_id = models.ForeignKey(Player, related_name='+')
    t_2_id = models.ForeignKey(Player, related_name='+')
    t_3_id = models.ForeignKey(Player, blank=True, null=True, related_name='+')
    t_4_id = models.ForeignKey(Player, blank=True, null=True, related_name='+')
    t_5_id = models.ForeignKey(Player, blank=True, null=True, related_name='+')
    t_6_id = models.ForeignKey(Player, blank=True, null=True, related_name='+')

Question: how to check the uniqueness of the selected player. those. so that in each field the player is unique. I came up with ideas when validating the form (I'm talking about the admin panel) to read the id of the selected players, check them through a loop, adding them to a temporary array, etc. But it turns out a lot of code. Please tell me if there are more serious and easier options?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Astrohas, 2017-08-18
@Bjornie

do m2m and don't reinvent the wheel.

class Team(model.Model):
    ...
   players  = models.ManyToManyField(Player)

In admin panel do filter_horizontal

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question