V
V
val1n0r2020-02-14 18:24:25
Django
val1n0r, 2020-02-14 18:24:25

How to properly organize ForeignKey relationships?

good time

there is a model

class user_alliance(models.Model):

    al_leader = models.OneToOneField(User,on_delete=models.CASCADE,related_name='alliance_leader') # Кому принадлежит клан
    al_member = models.ForeignKey(User,on_delete=models.CASCADE) # Участники

    al_name = models.CharField(default='Альянс',max_length=48)
    al_level = models.IntegerField(default=1)

    
    def __str__(self):
        return self.al_name


As can be seen above - an alliance model that has a leader and participants, how to correctly attribute many users to one alliance?

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-02-14
@bacon

first, pep8 and Django rules

class Alliance(models.Model):
    leader = ...
    member = ...
    name = ...
    level = ...

secondly, if the User can only be in one alliance, then it’s easier to create a custom User with a ForeignKey on the Alliance (well, a member is not needed then), and if in several then
class Alliance(models.Model):
    ...
    members = models.ManyToManyField(User)
    ...

note that in such cases the plural is accepted

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question