Carlos Gonzalez
Carlos Gonzalez

Reputation: 111

Django Joining Tables

I am trying to get the information from one table filtered by information from another table (I believe this is called joining tables).

I have these two models:

class Listing(models.Model):
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=500)
    price = models.DecimalField(max_digits=11, decimal_places=2, validators=[MinValueValidator(Decimal('0.01'))])
    category = models.ForeignKey(Category, on_delete=models.CASCADE, default="")
    imageURL = models.URLField(blank=True, max_length=500)
    creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator", default="")
    isOpen = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.id} | {self.creator} | {self.title} | {self.price}"

class Watchlist(models.Model):
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listingWatched", default="")
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userWatching", default="")

What I need to do is to get all the listings from a specific user Watchlist, the idea is to generate a page with all of the information of each of the listings that are in the user's watchlist. What should I do?

Thanks in advance!

Upvotes: 1

Views: 33

Answers (1)

Mattia
Mattia

Reputation: 1129

Since is a foreign key, in Django you can access the information by calling the attribute

For example:

my_user = Watchlist.objects.get(pk=1)
print(my_user.listing.title)

You can also access to that attrbute in a query in case you need to filter upwards some value

values = Watchlist.objects.all().filter(listing__title='MyTitle')
my_titles = [x.title for x in values]
print(my_titles)

Or in your case, if you want to list all the title for a specific user

values = Watchlist.objects.all().filter(user='foo_user')
my_titles = [x.listing.title for x in values]
print(my_titles)

More documentation here

Upvotes: 1

Related Questions