简体   繁体   中英

Is there a way to build dynamic models in Django?

I am currently building a project in Django, and I was wondering if is there a way to build a dynamic model. I want to create a model with a group of user, and the table structure is the following:

  • Group Name
  • User 1
  • User 2
  • User 3
  • User...

But I want to make users dynamic, I mean, if the group has only 2 users the model will only put 2 users fields in the model, and if the group has 10 user the model put 10 users fields in the model.

Does someone know a way to do this? Is it even possible?

I hope I made it clear enough for you guys. If you have any questions please post in the comments and I will answer as fast as I can. Sorry for the english tho! Not my main language.

Think this way. One group may have many users and one user can be in may groups you can use ManyToManyField .

So you need something like:

# default user model or custom user model
class User():
    ...

    def __str__(self):
        return self.username

class Group(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    users = models.ManyToManyField(User)

    class Meta:
        ordering = ['-id']

    def __str__(self):
        return self.title

this is not possible in django. because the models should be clear to make tables in database. but you can handle this with many-to-many relationship. as the django documents say link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM