Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7768749
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T15:59:36+00:00 2026-06-01T15:59:36+00:00

Let’s say I have these models: class A(models.Model): name = models.CharField(max_length=32) b = models.ForeignKey(B,

  • 0

Let’s say I have these models:

class A(models.Model):
    name = models.CharField(max_length=32)
    b = models.ForeignKey("B", null=True)
    def __unicode__(self):
        return self.name

class B(models.Model):
    name = models.CharField(max_length=32)
    def __unicode__(self):
        return self.name

And this view:

def DisplayIt(request):
    html = ""
    for a in A.objects.all():
        html += "<input type='text' value='" + a.b.name + "' />"

This works fine as long as every A has a reference to a B in field b. But, I have null=True on the b reference field. When b is None, an exception is thrown that NoneType has no function name, which is completely expected.

Obviously, I can do this:

def DisplayIt(request):
    somestring = ""
    for a in A.objects.all():
        if a.b is not None:
            somestring += a.b.name

BUT, I don’t want to do this if I don’t have to. So, is there a way to get b.name or None if b is None, WITHOUT putting an if a.b is not None: in each loop? My real world example is much more complex, and I am creating a temporary object for display out of actual database fields… suffice it to say I’d prefer not to have all of those if statements, and wasn’t sure if there was another built-in function to get there. I could also create a class method to get each of these foreign fields if they exist or blank if they don’t, but I’m not sure this is the best way to go, either.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T15:59:38+00:00Added an answer on June 1, 2026 at 3:59 pm

    Make the database do it for you.

    Use a cross-relation filter to get all A with a b with name which is not null:

    def DisplayIt(request):
        somestring = ""
        for a in A.objects.filter(b__name__isnull=False):
            somestring += a.b.name
    

    To do this such that dummy values are included when a.b is None, use the following:

    def DisplayIt(request):
        somestring = ""
        for a in A.objects.filter(b__name__isnull=False):
            somestring += a.b.name
        for a in A.objects.filter(b__name__isnull=True):
            somestring += "dummy value for missing b.name"
    

    Also, as a side note, don’t do string concatenation that way — it’s horribly inefficient, since Python strings aren’t mutable. The following is much better:

    def DisplayIt(request):
        stringparts = []
        for a in A.objects.filter(b__name__isnull=False):
            stringparts.append(a.b.name)
        for a in A.objects.filter(b__name__isnull=True):
            stringparts.append("dummy value for missing b.name")
        ''.join(stringparts)
    

    Second side note: The code above will perform a query to fetch a.b on each iteration of the for loop. That can be suuuuper slow. Consider using select_related to grab everything all in one go. Be wary, though – this can be slow too if your indexes aren’t set up correctly. After enabling this I’d sniff the queries and spend some quality time with your query planner to make sure you’re not doing any nasty non-indexed lookups.

    Revised code:

    def DisplayIt(request):
        stringparts = []
        for a in A.objects.filter(b__name__isnull=False).select_related():
            stringparts.append(a.b.name)
        for a in A.objects.filter(b__name__isnull=True).select_related():
            stringparts.append("dummy value for missing b.name")
        ''.join(stringparts)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's say I have the following models class Photo(models.Model): tags = models.ManyToManyField(Tag) class Tag(models.Model):
Let's say you have a class called Customer, which contains the following fields: UserName
Let's say on a page I have alot of this repeated: <div class=entry> <h4>Magic:</h4>
Let's say I have window.open (without name parameter), scattered in my project and I
Let's say I have one class User, and it has a property of type
Let's say you have a class library project that has any number of supplemental
Let's say I have an abstract parent class called shape, and that there are
Let's say that I have a model that handles recipes, and I want to
Let's say I'm building a data access layer for an application. Typically I have
Let's say we have a simple function defined in a pseudo language. List<Numbers> SortNumbers(List<Numbers>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.