我正在尝试创建一个有效的地址模型/ View /...,并且该模型可以正常工作,但我正在尝试访问它包含的数据,但它不起作用。这是模型:
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'
有人可以引导我获取登录用户的所有地址吗?
非常感谢!
最佳答案
过滤器约束users
引用中间多对多表的ID,因此会出现错误。您应该完整指定相关字段,其中 user
指的是 Profile.user
字段,username
指的是 User .用户名
字段:
allAddresses = Address.objects.all().filter(users__user__username='arturo')
关于python - 我怎样才能从这个模型中获取对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54935936/