【发布时间】:2018-07-02 16:33:22
【问题描述】:
我什至不知道如何找到解决方案,但让我们从头开始。
这些是我的模型:
class Animal(models.Model):
SPECIES = (
("DOG", "DOG"),
("CAT", "CAT"),
)
species = models.CharField(max_length=4, choices=SPECIES)
name = models.CharField(max_length=20)
weight = models.PositiveSmallIntegerField(null=False, blank=False)
age = models.PositiveSmallIntegerField(null=False, blank=False)
color = models.CharField(max_length=10)
isill = models.BooleanField(null=False)
isagressive = models.BooleanField(null=False)
isadopted = models.BooleanField(null=False)
isreturned = models.NullBooleanField()
whichbox = models.CharField(max_length=5)
photo = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
class MedicalHistory(models.Model):
animal = models.ForeignKey(Animal, on_delete=models.CASCADE)
disease = models.CharField(max_length=100)
medicine = models.CharField(max_length=20, null=True, blank=True)
therapy = models.CharField(max_length=50)
howmuchmed = models.CharField(max_length=50)
daterecord = models.DateField
def __str__(self):
return self.disease
这是我的网址:
urlpatterns = [
path('', AnimalListView.as_view(template_name='Animals/animals.html'), name='animallist'),
path('add/', AddAnimal.as_view(), name='addanimal'),
path('edit/<int:pk>/', EditAnimal.as_view(), name='editanimal'),
path('detail/<int:pk>/', AnimalDetailView.as_view(template_name='Animals/animaldetail.html'), name='animaldetail'),
path('medlist/<int:pk>/', MedhistoryListView.as_view(template_name='Animals/medlist.html'), name='medlist'),
]
和我的观点(只有两个)
class AnimalDetailView(DetailView):
queryset = Animal.objects.all()
def get_object(self):
object = super().get_object()
object.save()
return object
context_object_name = 'animal_detail'
class MedhistoryListView(ListView):
"PLACE FOR CODE"
context_object_name = 'medical_history_list'
在 MedhistoryListView 中,我想展示一种动物患有的疾病。 AnimalDetailView 模板上有指向 Medhistorylistview 的 url 的链接。我的主要问题是如何将主键从一个视图保存到另一个视图,并仅选择这些具有指定 animal.pk 的对象。就像 MedicalHistory.objects.get(animal.pk=pk)。谁能帮帮我?
【问题讨论】:
-
通过链接中的 URL 传递 PK。
-
为什么要保存在详细视图中?
-
我可以看到
detail/<int:pk>/,你在animaldetail中传递了什么pk? -
这是一种动物的主键。在这个 url 中是关于一个对象的所有信息,pk 是这个对象的主键。
标签: python django django-class-based-views