我正在尝试创建一个有效的地址模型/视图/ ...,并使该模型正常工作,但是我试图访问其中包含的数据,但该模型不起作用。这是模型:
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'
有人可以引导我获取登录用户的所有地址吗?
非常感谢您!
答案 0 :(得分:2)
过滤器约束users
是指中间多对多表的ID,因此是错误。您应该改为完整指定相关字段,其中user
指Profile.user
字段,而username
指User.username
字段:
allAddresses = Address.objects.all().filter(users__user__username='arturo')