[Fixed]-Model properties returning empty

1👍

Ah of course, now I see it. The error says it – you’re trying to use streets as a column in your filter() expression, but it is not a db column defined anywhere. You need to define the column as an ancestor of Field class (+ make a migration for it), and then you can use it in your db query.

You have to also rename the property streets so something else, if the db column will be called that way.

edit for the comment below: you can have both the things, but they cant obviously have the same name. So for example this way:

class Vehicle(models.Model):

    # ...
    # a singular name
    street = models.CharField(max_length=128)

    @property
    def streets(self): # plural
        # you can use this instead of the 3 lines with `if` you have now
        name_substr = self.name.split()[0]

        #since the column is singular `street`, is needs to be singular in the query below too.
        return LandVehicle.objects.filter(Q(street__name__contains=self.name) |
                                          Q(street__name__contains=name_substr) |
                                          (Q(street__lat__range=[self.lat - self.radius, self.lat + self.radius]) &
                                           Q(street__lon__range=[self.lon - self.radius, self.lon + self.radius])))

As for your question what does LandVehicle.objects.filter() do is that it is a handy way to to write an sql query without actually writing the raw SQL query. Django then translates it into the query for you. So when you want to filter the db records by a street name, you have to have the street column in database, so the database can do the comparison above the data.

For example this bit: Q(street__name__contains='foobar') is translated to an sql query like select * from vehicle where street LIKE '%foobar%'. So obviously it is expected the column street needs to be there. Not only for filtering the data, but you also need to store these data.

If you dont understand how Django ORM works, go read this part of documentation: https://docs.djangoproject.com/en/1.10/topics/db/queries/

Leave a comment