Home > Back-end >  Is there a way to add list in a django model class?
Is there a way to add list in a django model class?

Time:08-06

I'm a django beginner and trying to make a project from scratch. My models are :

class Citizen(models.Model):
    name = models.CharField(max_length=64, unique=False)
    citizen_id = models.CharField(max_length=10, unique=True)

    def __str__(self):
        return '{} by {}'.format(self.name, self.citizen_id)


class Manager(models.Model):
    name = models.CharField(max_length=64, unique=False)
    manager_id = models.CharField(max_length=10, unique=True)

    def __str__(self):
        return '{} by {}'.format(self.name, self.manager_id)


class Message(models.Model):
    sender = models.ForeignKey(Citizen, Manager, on_delete=models.CASCADE, related_name='sender')
    receiver = models.ForeignKey(Citizen, Manager, on_delete=models.CASCADE, related_name='receiver')
    message = models.CharField(max_length=1200)
    timestamp = models.DateTimeField(auto_now_add=True)
    is_read = models.BooleanField(default=False)

    def __str__(self):
        return self.message

    class Meta:
        ordering = ('timestamp',)


class Centre(models.Model):
    pass

In Centre , there's gonna be one manager and then a lot of citizens. What should I do here? Should I add a list of citizens? Is that possible?

CodePudding user response:

I think reading this might help.

But essentially you'd want to implement what's called a One (Centre) to Many (Citizen) relationship. In short your citizen can have a Foreign Key called centre_id which will be the id of the centre they belong to. And then you can use the id of the Centre to query a list of citizens, or if you want to fetch the centre and attach a list of it's citizens to it, then you can do something which is called a join

CodePudding user response:

You can implement this in two different ways:

  1. Set a ForeignKey field on your citizen model. This is a many-to-one relationship meaning that one Centre can have many Citizens. You can set the Centre on the Citizen object, the centre can be accessed as citizen.centre and in verse as centre.citizen_set.all()
class Citizen(models.Model):
    ...
    centre = models.ForeignKey(Centre, null=True, blank=True, on_delete=models.SET_NULL)
  1. If there is only one Manager per Centre then you can use a OneToOneField to ensure that there aren't multiple managers. It works differently to a many-to-one relationship as it is completely two-way, e.g. manager.centre and centre.manager.
class Manager(models.Model):
    ...
    centre = models.OneToOneField(Centre, ...
  • Related