Python:如何在我的Django模板中传递外键的值?

时间:2016-07-19 16:38:41

标签: django django-models foreign-keys django-views

我创建了一个出价模型,这样第二类用户就可以对某些帖子进行出价'由type-1用户创建。为实现这一目标,我在模型' Bid'。

中为post field创建了一个外键

实际上,我想将出价与特定帖子相关联,并使用自动生成的ID'在'帖子'模型。所以我把get_absolute_url放在Post' id'旁边。在我的模板中。我是django的新手,我不确定它是否适用于我想要的东西。

如何将出价与post_id相关联到模板中的特定帖子,以便我可以获得各种类型2用户针对特定帖子的出价金额?我很乐意帮助我解决这个问题。

这是我的代码:

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)

    objects = PostManager()

    def __str__(self):
        return self.post_id

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"id": self.post_id})

    class Meta:
        ordering = ["-timestamp", "-Time"]

class Bid(models.Model):

    bid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    post = models.ForeignKey(Post, default=uuid.uuid4, 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.bid_id})

    def __unicode__(self):
        return self.amount

    def __str__(self):
        return self.amount

forms.py:

class BidForm(forms.ModelForm):
    // Defined a post field as ModelChoiceField
    post = forms.ModelChoiceField(queryset= Post.objects.all(), label="Post", widget=forms.RadioSelect(), initial=0)
    amount = forms.IntegerField(help_text='Place the bid for a Post')

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(BidForm, self).__init__(*args, **kwargs)
        self.fields['post'].queryset = Post.objects.all

    class Meta:
        model = Bid
        fields = ["amount"]

views.py:

def live_bid_truck(request, **kwargs):
    if request.method=='post':
        form = BidForm(request.POST or None)

        if  form.is_valid():
         bid = form.save(post)
         bid = form.save(commit=False)
         print(form.cleaned_data.get('amount'))
         bid.user = request.user
         bid.post = form.cleaned_data['post'] // Set my post here


         bid.save()
    else:
        form=BidForm()
        post_queryset = Post.objects.all()
        context = {
        "post_queryset": post_queryset, 
        "title": "List",
        'form': form,

    }
        return render(request, 'loggedin_truck/live_bid_truck.html', context)

live_bid_truck.html

{% for post in post_queryset %}
<table class="table table-striped, sortable">
    <thead>
        <tr>

            <th>Load No.</th>
            <th>From</th>
        </tr>
    </thead>
    <tbody>
        <tr> // Returns the post_queryset with radio buttons
            <td >{{form.post}} </td>
            <td>{{ post.from1 }}</a><br/></td>
        </tr> 
    </tbody>
</table>
<table class="table table-striped, sortable "  style="margin-top: 10px">
    <thead>
        <tr>
            <th> Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr>     
            <form class="nomargin" method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
            <td>{% render_field  form.amount  class="form-control" %}</td>
        </tr>
     </tbody>
 </table>

<input type='submit' value='Post Bid'/></form>

{% endfor %}

更新 - 1:

Views.py:

def live_bids(request):
    post_queryset = Post.objects.all().prefetch_related('bids')
    bid_queryset = Bid.objects.all().order_by('amount')

    context = {
        "post_queryset": post_queryset,
        "bid_queryset": bid_queryset,
        "title": "List",
    }
    return render(request, 'loggedin_load/live_bids.html', context)

live_bids.html:

{% for post in post_queryset %}
{{post.id}}
{% for bid in post.bids.all %}
{{bid.amount}}
{% endfor %}
{% endfor %}

1 个答案:

答案 0 :(得分:5)

如果我理解正确,目标是能够在帖子上列出相关的投标人/出价?如果是这样,那么您可以使用select_related prefetch_related(如果您从孩子那里选择父母)following the backward relation(如果您正在进行反向查询)

1)首先,在您的投标模型中,related_name会更好地{&#34;出价&#34;,就像这样;

post = models.ForeignKey(Post, default=1, related_name='bids' )

2)其次在def live_bid_truck(request):里面进行这样的帖子查询,这样你就可以在一个数据库中获得所有相关对象。;

Post.objects.all().prefetch_related('bids') 

3)然后在您的模板中,您可以使用可以访问帖子的相关出价

{% for bid in post.bids.all %} // In your case post is obj
    {{ bid }}  // Access whatever you need from the bid like {{ bid.user }}
{% endfor %}

即使没有http://codepen.io/johnwaynerui/pen/bZvRLm的预取,您也应该可以致电post.bids.all并接收值。如果您没有获得任何值,那么您可能没有正确设置它们。随着帖子数量的增加,prefetch_related有助于提升效果。

从您的代码

BidForm中没有post的引用,我也不知道你是否在自定义save()方法中使用它。保存此表单时,post_id将是默认值1

# NO REFENCE TO post
class BidForm(forms.ModelForm):

 class Meta:
    model = Bid
    fields = ["amount"]  

同样在您的view中,您也不要设置帖子。

def live_bid_truck(request):

    form = BidForm(request.POST or None)

    if  form.is_valid():
        bid = form.save(commit=False)

        print(form.cleaned_data.get("amount"))
        bid.user = request.user # YOU SET THE USER 
        bid.post = ?? # YOU DON'T SET THE POST HERE EITHER, 
                      # SO ALL YOUR BIDS HAVE THE DEFAULT POST id = 1
                      # DO YOU ACTUALLY HAVE POST with id = 1?

        bid.save()

        # WHAT HAPPENS IF YOU PRINT BID POST ID HERE ?? 
        # CHECK HERE IF YOU REALLY HAVE THE RELATED POST ID.
        print(bid.post.id)