Skip to content
Advertisement

A count of ForeignKey

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

JavaScript

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.

JavaScript

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

JavaScript

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?

Advertisement

Answer

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.



Edit:

According to the current picture, a Event can have more than one Team as well as more than one User. So, make two separate Foreign keys for both the models.

models.py

JavaScript

admin.py

JavaScript

views.py

JavaScript

home.html or template file:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement