Arturo
Arturo

Reputation: 4190

How can I get the objects from this model?

I'm trying to create an address model/views/... that works and I got the model working, but I'm trying to access the data it contains and it's not working. Here is the model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    nick_name = models.CharField('Nick name', max_length=30, blank=True, default='')
    bio = models.TextField(max_length=500, blank=True)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    # Address = models.ForeignKey('Address', on_delete=models.CASCADE)

    # If we don't have this, it's going to say profile object only
    def __str__(self):
        return self.user.username
        #return f'{self.user.username}'  # it's going to print username Profile

    def save(self, *args, **kwargs):
            super().save(*args, **kwargs)

            img = Image.open(self.image.path)

            if img.height > 300 or img.width > 300:
                output_size = (300, 300)
                img.thumbnail(output_size)
                img.save(self.image.path)


class Address(models.Model):
    users = models.ManyToManyField(Profile, blank=True)
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60, default="Miami")
    state = models.CharField(max_length=30, default="Florida")
    zipcode = models.CharField(max_length=5, default="33165")
    country = models.CharField(max_length=50)

    class Meta:
        verbose_name_plural = 'Address'

    def __str__(self):
        return self.name

I'm trying to access all the addresses that a user can have. I tried:

# TESTS
allAddresses = Address.objects.all()
print(allAddresses)

and for the address objects it gives me: <QuerySet [<Address: Elizabeth>, <Address: Work>]>

But if I try to filter it by user, like this:

allAddresses = Address.objects.all().filter(users='arturo')
print(allAddresses)

it gives me an error: invalid literal for int() with base 10: 'arturo'

Could someone lead me on the way to get all the addresses of the logged in user please?

Thank you very much!

Upvotes: 1

Views: 36

Answers (1)

blhsing
blhsing

Reputation: 106768

The filter constraint users refers to the ID of the intermediate many-to-many table, hence the error. You should specify the related fields in full instead, where user refers to the Profile.user field, and username refers to the User.username field:

allAddresses = Address.objects.all().filter(users__user__username='arturo')

Upvotes: 2

Related Questions