我收到一个错误,AttributeError:'DeferredAttribute'对象没有属性'objects'。 我想解析excel并把它放到模型中(City& Prefecture& Area& User)。我写了
user3 = User.objects.filter(corporation_id=val3).first()
if user3:
area = Area.objects.filter(name="America").first()
pref = Prefecture.objects.create(name="prefecture", area=user3.area)
city = City.objects.create(name="city", prefecture=pref)
price_u1000 = Price.upper1000.objects.get(city=city)
price_500_1000 = Price.from500to1000.objects.get(city=city)
price_u500 = Price.under500.objects.get(city=city)
pref.name = "NY"
pref.save()
for i in range(2,len(fourrows_transpose)):
city.name = fourrows_transpose[i][1]
city.save()
print(fourrows_transpose[i][1])
price_u1000.name = fourrows_transpose[i][2]
price_u1000.save()
print(fourrows_transpose[i][2])
price_500_1000.name = fourrows_transpose[i][3]
price_500_1000.save()
print(fourrows_transpose[i][3])
price_u500.name = fourrows_transpose[i][4]
price_u500.save()
print(fourrows_transpose[i][4])
Traceback说这段代码price_u1000 = Price.upper700.objects.get(city=city)
是错误的。
models.py是
class Area(models.Model):
name = models.CharField(max_length=20, verbose_name='area', null=True)
class User(models.Model):
user_id = models.CharField(max_length=200,null=True)
area = models.ForeignKey('Area',null=True, blank=True)
class Prefecture(models.Model):
name = models.CharField(max_length=20, verbose_name='prefecture')
area = models.ForeignKey('Area', null=True, blank=True)
class City(models.Model):
name = models.CharField(max_length=20, verbose_name='city')
prefecture = models.ForeignKey('Prefecture', null=True, blank=True)
class Price(models.Model):
upper1000 = models.CharField(max_length=20, verbose_name='u1000', null=True)
from500to1000 = models.CharField(max_length=20, verbose_name='500~1000', null=True)
under500 = models.CharField(max_length=20, verbose_name='d500', null=True)
city = models.ForeignKey('City', null=True, blank=True)
我该怎么做才能解决这个问题?我应该怎么写呢?
答案 0 :(得分:2)
因为upper1000或者ever字段没有属性对象。对象存在于Model类中。
如果upper1000,从500到1000和500以下是相互排斥的,你可以做这样的事情。但请记住,如果是这种情况,您应该在模型清理功能中处理互斥。
price_u1000 = Price.objects.filter(city=city, upper1000__isnull=False, from500to1000__isnull=True, under500__isnull=True)
我建议创建一个选择字段,而不是3个不同的字段,这些字段似乎是互斥的
class Price(models.Model):
UNDER_500 = 'under 500'
FROM_500_TO_1000 = 'from 500 to 1000'
UPPER_1000 = 'upper 1000'
PRICE_CHOICES = [
(UNDER_500, pgettext_lazy('Price under 500')),
(FROM_500_TO_1000, pgettext_lazy('Price from 500 to 1000')),
(UPPER_1000, pgettext_lazy('Price above 1000'))
]
price_range = models.CharField(
verbose_name=ugettext_lazy('Price range'),
max_length=25,
choices=PRICE_CHOICES,
default=UNDER_500
)
city = models.ForeignKey('City', null=True, blank=True)
def clean(self):
super(Price, self).clean()
# implement extra constraints here.
一些读物: https://docs.djangoproject.com/en/1.11/ref/models/querysets/