'How to get the objects from child model to a django template?
I have created child ('Bid') model related to a parent(Post) model in my Django project. I also created a BidForm which I have added in my B_Bid.view so that type-2 users can bid on a particular Post created by type-1 users. When bids are created to for a particular Post, I wanted to show them all distinguished with that post in my template. So, I did as in below code. But in my page, I couldn't able to get the list of the bids for a particular Post. I would appreciate helping me solve this.
Models.py:
class Post(models.Model):
post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
from1 = models.CharField(max_length=20)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
return self.post_id
class Bid(models.Model):
bid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
post = models.ForeignKey(Post, default=1, related_name='bids' )
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, unique=False)
amount = models.IntegerField()
def get_absolute_url(self):
return reverse("accept_bid", kwargs={"bid_id": self.id})
def __unicode__(self):
return self.amount
def __str__(self):
return self.amount
Views.py:
def place_bid(request):
form = BidForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
print(form.cleaned_data.get("amount"))
instance.user = request.user
instance.save()
queryset = Post.objects.all()
context = {
"object_list": queryset,
"title": "List",
"form": form,
}
return render(request, 'loggedin_truck/live_bid_truck.html', context)
def live_bids(request):
post_queryset = Post.objects.all().prefetch_related('bids')
context = {
"post_queryset": post_queryset,
"title": "List",
}
return render(request, 'loggedin_load/live_bids.html', context)
form.py:
class BidForm(forms.ModelForm):
class Meta:
model = Bid
fields = ["amount"]
live_bids.html:
{% for post in post_queryset %}
{{post.post_id}}
{% for bid in post.bids.all %}
{{bid.bid_id}}
{{bid.amount}}
{% endfor %}
{% endfor %}
Solution 1:[1]
To access child records, use
foo_set.all
Change your code to this
{% for post in post_queryset %}
{{post.post_id}}
{% for bid in post.bid_set.all %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Oneflydown |