Multiple attribute column in Django Models

(Yadnesh Salvi) #1

Can I add a column which can hold multiple values in a Django model?
For eg. I am making a site which contains various hotes and I want to list the facilities these hotels provide. So can I make this facilities column a multi-valued attribute?

(Vitor Freitas) #2

For simple string values (like tags) you could use an ArrayField (if you are using PostgreSQL database):

https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/

But then depending on the requirements, maybe creating an additional model will help. Something like this:

class Hotel(models.Model):
    name = models.CharField(max_length=30)
    # other fields...

class Facility(models.Model):
    hotel = models.ForeignKey(
        Hotel, 
        on_delete=models.CASCADE, 
        related_name='facilities'
    )
    description = models.TextField(blank=True)
    # other fields...

Note the related_name attribute. This will create a reverse relationship on the Hotel model where you can use it like a list:

hotel = Hotel.objects.create(name='Hilton Hotel')

# add facilities
hotel.facilities.create(description='facility 1')
hotel.facilities.create(description='facility 2')

# list facilities
hotel.facilities.all()
# out: [<facility 1>, <facility 2>]
2 Likes