0

How can I create a model with a field that is having a list of values? (For example a model called group with multiple members) Is it possible to implement the relationship with many to many fields?

3 Answers 3

1

Here is a example with multiple selection options

class Members(models.Model):
    MEMBERS = {
        (0, 'James'),
        (1, 'Jeremy'),
        (2, 'Alex'),
    }

    number = models.PositiveSmallIntegerField(default=0)
    names = models.PositiveSmallIntegerField(default=0, choices=MEMBERS)
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is describing multiple choice where only one value is selected at a time. Whereas the question is asking about choosing multiple values to be selected at the same time.
1

You are looking for Many2Many Field. For example:

class User(models.Model):
    # relevant fields
    ...

class Team(models.Model):
    # other fields
    members = models.ManyToManyField(User, related_name='teams')

Note several things about this solution:

  • Users can be members of multiple teams (that is why Many2Many relationship)
  • User model can reference all teams, he is part of: user.teams_set

If you want a User to be member of only one team, than ForeignKey is the right way to go:

class User(models.Model):
    # other fields
    team = models.ForeignKey('Team')
    ...

class Team(models.Model):
    # relevant fields
    ...

For more information consult documentation: https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/

3 Comments

Thanks for the answer @LynxLike. Also how can I add data to the many to many field?
You simply add appropriate model instance to the field. In your example: team = Team.objects.create(...) and user = User.objects.create(...). Then you simply assing the user to the team via team.members.add(user)
When I tried printing team.members after team.members.add(user) team.save() and then it is showing like User.None which means the data is not getting saved to the instance. How can I fix this issue ?
0

I do this one time. if you working with the PostgreSQL database in Django projects, in my search you can do like this

from django.contrib.postgres.fields import ArrayField

class MyModal (models.Model):
    array_field= ArrayField(models.IntegerField(null=True,blank=True),null=True,blank=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.