Home > Blockchain >  A count of ForeignKey
A count of ForeignKey

Time:06-23

I have class Team, which means a group of users. And the relation with User is One-to-Many.

class Team(models.Model):
        member = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)

But Team may consist of 2 and N members. I think to write manually is not our way, because it depends on count of people which is always variable.

 class Team(models.Model):
    member1 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)   
    member2 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    member3 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)

How can I do it more elegant and rational? I mean to connect count variable and ForeignKeys associating with users.

upd 15:17 UTC. I still don't understand how to make this. Sorry. So, let's begin to draw. enter image description here

For example, I wrote simple code

class Event(models.Model):
    id_user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)

But when I go to admin panel to add Event, I can add only one user. But I need to add a lot of users, who want to participate in the Event and then to divide them into Teams. I think I don't need another class Member. It seems unnecessary. Am I wrong?

CodePudding user response:

Create a team with one field team_name:

class Team(models.Model):
    team_name = models.CharField(max_length=1000) 

and assign users to this team:

class User(models.Model):
    this_users_team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) 

in this case you can assign as many Users to any team, as you want

CodePudding user response:

As you stated Team model, have ManyToOne relation that means ForeignKey.

But Team may consist of 2 and N members.

You should create two models Team and Member. In Member model, you can store all information related to members such as their age, gender, city, etc.

In Team model, you can store information related to particular team which consists of more than one Member i.e. It has ManyToOne relation with Member.

Models.py:

from django.db import models
from django.contrib.auth.models import User


class Member(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

    def __str__(self) -> str:
        return f"{self.user.username}"


class Team(models.Model):
    member = models.ForeignKey(Member, on_delete=models.SET_NULL, null=True)

Registering in admin site:

admin.py:

@admin.register(Member)
class MemberAdmin(admin.ModelAdmin):
    list_display = ['id', 'user'] #Also specify other fields.


@admin.register(Team)
class TeamAdmin(admin.ModelAdmin):
    list_display = ['id', 'member'] #Also specify other fields.
  • Related