我有3个模型
我是否需要更改模型中的连接,并使关键字段不是ID,而是名称?
class Category(models.Model):
name = models.CharField(max_length=150, unique=True)
description = models.CharField(max_length=250)
class Company(models.Model):
name = models.CharField(max_length=150, unique=True)
country = models.CharField(max_length=50)
class Motobike(models.Model):
name = models.CharField(max_length=150)
company = models.ForeignKey('Company', on_delete=models.CASCADE)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
并进行测试:
def test_category(setup):
client = Client()
category_id = Category.objects.get(name='Мотоциклы').id
response = client.get(f'/categories/{category_id}/')
assert response.status_code == 200
response_data = json.loads(response.content.decode('utf-8'))
assert len(response_data) == 2
assert response_data[1]['name'] == 'Ninja Turbo'
assert response_data[1]['vendor'] == 'Kawasaki'
assert response_data[1]['category'] == 'Мотоциклы'
assert response_data[1]['description'] == ''
response = client.get(f'/categories/25/')
assert response.status_code == 404
我认为:
class CategoryView(DetailView):
model = Category
template_name = 'bikes_site/categories_detail.html'
def get_context_data(self, id, **kwargs):
context = get_object_or_404(self.model, id)
context['motobikes'] = Motobike.objects.filter(category_id=id).all()
return context
我收到一个错误:
get_context_data()
缺少1个必需的位置参数:'id'
答案 0 :(得分:1)
get_context_data
的函数签名应该是错误的
def get_context_data(self, **kwargs):
//todo
您的详细信息视图应该这样
class CategoryView(DetailView):
model = Category
template_name = 'bikes_site/categories_detail.html'
pk_url_kwarg = "id"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
category = self.get_object()
context['motobikes'] = Motobike.objects.filter(category_id=category.pk)
return context