【问题标题】:How can I get the objects from this model?如何从此模型中获取对象?
【发布时间】:2019-02-28 23:37:35
【问题描述】:

我正在尝试创建一个有效的地址模型/视图/...,并且模型可以正常工作,但我正在尝试访问它包含的数据,但它无法正常工作。这是模型:

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

我正在尝试访问用户可以拥有的所有地址。我试过了:

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

对于它给我的地址对象:<QuerySet [<Address: Elizabeth>, <Address: Work>]>

但如果我尝试按用户过滤它,像这样:

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

它给了我一个错误:invalid literal for int() with base 10: 'arturo'

有人可以带我去获取登录用户的所有地址吗?

非常感谢!

【问题讨论】:

    标签: python django django-models django-rest-framework django-views


    【解决方案1】:

    过滤约束users指的是中间多对多表的ID,因此报错。您应该完整地指定相关字段,其中user 指的是Profile.user 字段,username 指的是User.username 字段:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多