Home > OS >  making django model field that is a foreign key pointing to a model field in different app taking ar
making django model field that is a foreign key pointing to a model field in different app taking ar

Time:04-05

I'm new to django rest framework, what I'm trying to achieve is to create a model field that is a foreign key and points to a different app model and take their user_id(the automatic id that is predefined)

users\models.py

class user(models.Model):
    username = models.CharField(max_length=10, unique=True)
    name = models.CharField(max_length=64)
    creationtime = models.DateTimeField(auto_now_add=True)
    userdescription = models.CharField(max_length=250)
    
    def __str__(self) -> str:
        return self.username

teams\models.y

class team(models.Model):
    teamname = models.CharField(max_length=64)
    description = models.CharField(max_length=128)
    creationtime = models.DateTimeField(auto_now_add=True)
    admin = models.ForeignKey(user, related_name='admin', on_delete=models.CASCADE)
    members = models.ForeignKey(user, related_name='members', on_delete=models.CASCADE)

    def __str__(self) -> str:
        return self.teamname

so what I want is like when I see the members column in database it should show an array of user_id, something like this:

members: [1,2,5,7,8]

these number refers to the automatic index that is created for each row or you know like when we do a get request for a specific user_id like: https://localhost:8000/users/1/

thanks in advance for the help.

CodePudding user response:

You can go for the many to many relationship as it would create and intermediate table referring to the user and the team

members = models.ManyToManyField(user,help_text='Select members for this team')

CodePudding user response:

You should do it the opposite way.

Each user should have team field (foreign key) with a related_name = “members”.

Then if you want to get all members of the team you can use the related name.

(In Django there only manyToOne and not OneToMany)

users\models.py

class user(models.Model):
   . . .

  team = models.ForeignKey(user, related_name='members', on_delete=models.CASCADE)

teams\models.y

class team(models.Model):
    teamname = models.CharField(max_length=64)
    description = models.CharField(max_length=128)
    creationtime = models.DateTimeField(auto_now_add=True)
    admin = models.ForeignKey(user, related_name='admin', on_delete=models.CASCADE)
 

    def __str__(self) -> str:
        return self.teamname
  • Related