Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get one field from model in django

I have such a model, in my django application. I want to draw only one field of this model and put them in the view. My solution below does not work:

obj = Text.objects.get(subsID)

My model

result = braintree.Subscription.create({
        "payment_method_token": payment_method_token,
        "plan_id": "67mm"
        })

subscription_id = result.subscription.id

class Text(models.Model):
    title = models.CharField(max_length=255)
    text = models.TextField()
    date_from = models.DateTimeField('date from', blank=True, null=True)
    date_to = models.DateTimeField('date to', blank=True, null=True)
    subsID = models.CharField(default=subscription_id, max_length=255)

    def __unicode__(self):
        return self.title

My view

def get_history(request):
    subscription_id = Text.objects.filter(subsID)
    history = braintree.Subscription.find(subscription_id)
    return render(request, "sheet/history.html", {"history": history})
like image 287
mark Avatar asked Mar 27 '15 08:03

mark


People also ask

How do you get all fields of models in Django?

Retrieving all field instances of a modelinclude_parents. True by default. Recursively includes fields defined on parent classes. If set to False , get_fields() will only search for fields declared directly on the current model.

How do you value a field in Django?

To receive a value you need to get the Field bound to an instance. Which is usually done by: MyModel. objects. get(some_query).


1 Answers

Generally, When filter or get, you have to put query inside it, like

subscription_id = Text.objects.filter(fieldname="searchterm")

This will return a queryset.So to view this

subscription_id.values() #returns a list of objects(dicts)

If you want to get only subsID

subscription_id.values("subsID")

This also return you list which contains

[{"subsID":"value"}, {"subsID":"value"} ....]

If you want to get only values

subscription_id.values_list("subsID", flat=True)

This will return like

["value", "value", ....]
like image 129
itzMEonTV Avatar answered Sep 23 '22 04:09

itzMEonTV