Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a django model as a field for another model?

I have been tasked with creating Django Models for a hypothetical apartment booking application.

My question is: can I use a model that I've defined, as a field in another model?

For example, I will have one model called "Listing" that represents an apartment being listed.

class Listing(models.Model):
    address = models.IntegerField()
    owner = models.CharField(max_length=256)
    duration =  models.DurationField()
    price= models.IntegerField()

I also want to have a "Booking" model that represents an apartment once someone has booked it. It will have the exact same info as a Listing, with the addition of the username of the person who booked it. So can I have my Booking model use Listing as a field? And then just have one extra field for the booker's username.

Any other tips/critiques are highly appreciated as I am a complete beginner at Django.

like image 703
Kelly Avatar asked Dec 19 '22 03:12

Kelly


1 Answers

I'm not 100% sure what you mean by use Listing as a field

But to me, you should be looking at the different built-in model relationships that exist in Django.

In your particular case, you will probably want to use a One-to-One relationship like so,

class Listing(models.Model):
    address = models.IntegerField()
    owner = models.CharField(max_length=256)
    duration =  models.DurationField()
    price= models.IntegerField()

class Booking(models.Model):
    listing= models.OneToOneField(
    Listing,
    on_delete=models.CASCADE,
    )
    username = models.Charfield()

Now if a user can book more than one apartment at a time, you'll be interested in a ForeignKey relationship like so,

class Listing(models.Model):
    address = models.IntegerField()
    owner = models.CharField(max_length=256)
    duration =  models.DurationField()
    price= models.IntegerField()

class Booking(models.Model):
    listing= models.ForeignKey(
    Listing,
    on_delete=models.CASCADE,
    )
    username = models.Charfield()

Note that in both examples I used Charfield for the username, feel free to use whatever Django field you need.

like image 52
scharette Avatar answered Dec 20 '22 17:12

scharette