Sascha Wick Sascha Wick - 28 days ago 7
Ajax Question

Get the ChildObject from the BaseObject

So i want to get the Secondobject

It's One to One from First.


model.py(First)



class Firstobject(models.Model):
(...)
def save(self,*args,**kwargs):
super().save(*args,**kwargs)
Second.objects.get_or_create(first=self)


model.py(Second)



class Votes(models.Model):
(...)
first = models.OneToOneField(First)
def save(self,*args,**kwargs):
self.value2 = self.value - self.value2
super().save(*args,**kwargs)
def __str__(self):
return "%s name" % self.first


View.py



def function(request, pk):
pk = request.GET.get('pk')
obj = models.First.objects.get(pk=pk)
votes = obj.Second
votes.value = votes.value + 1
votes.save()
data = {'val1':votes.value, 'val2':votes.value2}
return JsonResponse(data)


Index.html



<button
data-url="{% url 'first:link' pk=first.pk %}"
data-pk="{{first.pk}}"></button>


foo.js



$('button').click(function() {
var pk = $(this).attr("data-pk");
var urla = $(this).attr("data-url"); //
$.ajax({
url : urla,
data : {'pk' : pk},
success : function(data) {
$('#ID1' + pk).text(data.val1)
$('#ID2' + pk).text(data.val2)}
});
});


So my Error is:



AttributeError at /link/5/ 'First' object has no attribute 'Second'


I know whats the error is, but i cant figure out how to fix it.

The Error is in views.py. I cant just
First.Second
. So can you tell me what method i should use?

Answer Source

Do add related_name

first = models.OneToOneField(First, related_name="second")

Then you can do

obj = models.First.objects.get(pk=pk)
votes = obj.second