1👍
atrocity.location
is a ForeignKey
, so it points to a single City
. With your current model, you should just use
city = atrocity.location
to retrieve the single city associated with an Atrocity
. You use .all()
on a manager object representing a bunch of objects, such as City.objects
, but your location
field is just a single object.
If you want the Atrocity.location
field to represent many cities, then you can use
location = models.ManyToManyField(City)
and call atrocity.location.all()
to get all the location cities for atrocity
.
Edit: It seems from your code that you might be trying to get a list of all cities which are the location for some Atrocity
? If that’s the case, you could use
cities = list(set(map(lambda a: a.location, Atrocity.objects.all()))
and pass cities
into your template. This gets the the location
of each Atrocity
object, and combines them into a set to remove duplicates.
0👍
Location is a foreign key. A foreign key references only one model. Then your code has no sense because .all()
method is for query sets. Should be just:
cities = atrocity.location
- [Answer]-Apache can't load utf8 python file
- [Answer]-NoReverseMatch exception in a simple Django app
- [Answer]-Django csrf in mobile apps
0👍
What you are doing is wrong. There is a foreign key relationship so, each atrocity is related to only one location. So, you can not use all
Example:
#Each Atrocity is related to only one location
city = atrocity.location
#Each can be related to more than one atrocity
atrocities = location.atrocity_set.all()
And instead of looping through each Atrocity object to collect the city. It would be more efficient to do it on the database level. You can do a join query between City and Atrocity via this.
cities = City.objects.filter(id__in = Atrocity.objects.values_list('location', flat=True))
- [Answer]-How to overwrite the default email message for user account activation in django-userna?
- [Answer]-POST_BUFFER = "0" not working as expected