我目前有一个简单的models.py页面
from django.db import models
class itemType(models.Model):
typeName = models.CharField(max_length = 120)
pub_date = models.DateTimeField(auto_now_add=True, auto_now = False)
def __str__(self):
return self.typeName
class item(models.Model):
itemName = models.CharField(max_length = 120)
price = models.DecimalField(max_digits=5, decimal_places=2)
descip = models.TextField
slug = models.SlugField(max_length = 70)
itemFront = models.ImageField( upload_to = "Images")
itemBack = models.ImageField( upload_to = "Images")
pub_date = models.DateTimeField(auto_now_add=True, auto_now = False)
itemtype = models.ForeignKey('itemType')
def __str__(self):
return self.itemName
现在我想把这些信息放到我的views.py页面上,但我不明白如何转移它
def shop(request):
context = {
}
return render(request,"shop.html" , context)
答案 0 :(得分:6)
如何导入:
MyBar readMyBar(JsonReader)
PS:类名称应为 UpperCamelCase
(from appname.models import ItemType, Item
,Item
)
如何使用(随机示例):
ItemType
<强>更新强>
更好的方法是导入整个模块(如果需要,给它一个别名)并使用as(假设上面的例子),
def shop(request):
context = {
'items': Item.objects.filter(name='xyz'),
'types': ItemType.objects.all()
}
return render(request, "shop.html", context)
PS:始终尽量避免在代码中使用from appname import models as appname_models
def shop(request):
context = {
'items': appname_models.Item.objects.filter(name='xyz'),
'types': appname_models.ItemType.objects.all()
}
return render(request, "shop.html", context)
。阅读this了解最佳导入做法。
答案 1 :(得分:0)
您可以尝试这样的事情。
from appname.models import ItemType,Item
or
from appname.models import *
def shop(request):
data = Items.objects.all()
context = {
'items': data,
}
return render(request, 'template.html', context)
答案 2 :(得分:0)
from .models import *
或
from .models import ItemType,Item
答案 3 :(得分:-2)
from _appname_.models import *