1

I have model that looks like this:

class Beacon(models.Model):
    name = models.CharField()
    bid =  models.CharField()
    campaigns = models.ManyToMany(Campaign)
    location = models.ForeignKey(Location)

In my api view, I am trying to find a specific Beacon given a bid (this is beacon id btw). So I have something that looks like this:

def SawBeacon(request, beacon_id):

    if request.method == 'GET':
        Beacon  = Beacon.objects.filter(bid__beacon_id=%s) % beacon_id

This doesn't work.. But I think you get the idea of what I am trying to do. I want to take the incoming beacon_id argument and filter down to a specific beacon that matches this ID.

  1. How would I do this?
  2. When I filter down an object, do I get the object itself or will I get the value?
2
  • What about: Beacon.objects.filter(bid__beacon_id=(%s) % (beacon_id))? Commented May 14, 2014 at 16:46
  • Question: I actually don't know if the "bid__beacon_id" part is correct. More specifically the "beacon_id" part .I am just copying previous examples. Commented May 14, 2014 at 17:01

1 Answer 1

2

If you're getting one instance, you'll want to use get rather than filter. Try:

Beacon.objects.get(bid=beacon_id)

When you use filter, you'll return a queryset.

Sign up to request clarification or add additional context in comments.

4 Comments

I think he's actually looking for Beacon.objects.get(id=beacon_id)
But isn't bid his field for beacon_id?
Correct. Filter returns a queryset, even if there's only one instance in the queryset.
Get will also throw an error if the object doesn't exist so you should always anticipate this with a try except statement. You can use django.core.exceptions ObjectDoesNotExist to check for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.