Strike
Strike

Reputation: 95

Django Model data in views as variable

Need help, Very new to Django.

I have created a model as below

class Redirect_url(models.Model):
    hosturl = models.CharField(max_length=100)
    path = models.CharField(max_length=100)
    redirectpage = models.CharField(max_length=200)

I need the hosturl, path and redirectpage as a variable in my views page for me to make some logic before I render to the html page. I don’t know

from django.shortcuts import render,redirect
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from .import models

def home(request):
    return render(request,'home.html')

def redurl(request):
    b = request
    data = (models.Redirect_url.objects.all())
    print(data)
    return HttpResponse(data, content_type="text/plain")

I am getting print as Redirect_url object (1)Redirect_url object (2). How to get all the models data. Thanks.

Upvotes: 0

Views: 109

Answers (2)

Pruthvi Barot
Pruthvi Barot

Reputation: 2018

import json

data = Redirect_url.objects.all()
list = []
for record in data:
    dict = {'Host URL':record.hosturl,'Path':record.path,'Redirect Page':record.redirectpage}
    list.append(dict)
    list_as_json = json.dumps(list)
return HttpResponse(list_as_json)

Redirect_url.objects.all() will return queryset which contains number of obhects that we have stored in database by iterating over queryset you can get all objects one by one. you can do number of operations on queryset as below: django queryset

Upvotes: 0

stackoverflowusrone
stackoverflowusrone

Reputation: 536

models.Redirect_url.objects.all() returns a list of QuerySets. You can iterate through the list with for loop and access the properties.

You can also add __str__() method in your model for better representation, see here.

You should check basic Django tutorial to understand it better.

Upvotes: 1

Related Questions