Issue
I have a model Post
with some fields. Aside from that I have some models which have Post
as a ForeignKey
.
Some examples are:
class ViewType(models.Model):
post = models.ForeignKey(
Post,
on_delete=models.CASCADE,
related_name="view_types",
verbose_name=_("Post"),
)
view = models.CharField(
max_length=20, choices=VIEW_TYPE_CHOICES, verbose_name=_("View")
)
...
class HeatType(models.Model):
post = models.ForeignKey(
Post,
on_delete=models.CASCADE,
related_name="heat_types",
verbose_name=_("Post"),
)
heat = models.CharField(
max_length=30, choices=HEAT_TYPE_CHOICES, verbose_name=_("Heat")
)
...
So what I want to do here is somehow get a dictionary with all the values of those fields in my view. For example instead of doing this for all of the models that have Post
as a ForeignKey
:
heat_type = HeatType.objects.filter(post=post)
view_type = ViewType.objects.filter(post=post)
dict = {
"view_type": view_type.view,
"heat_type": heat_type.heat,
etc...
}
get all the relevant related fields in one go. Is there a simpler solution for that? Or do I have to manually get all queries for each model? Thanks in advance
Solution
With some trepidation....
class Post(models.Model):
def dump(self):
mydict = {}
for k, v in Post.__dict__.items():
# find the attributes that represent the reverse foreign keys
if type(v) == ReverseManyToOneDescriptor:
print(k)
mydict[k] = getattr(self, k).all()
print(mydict)
With that solution, each value in mydict
has a list of instances, but not the values of heat
and view
respectively. What you might do is add a methods to HeatType
and ViewType
that have the same name, like so
class ViewType(models.Model):
def dump(self):
return self.view
class HeatType(models.Model):
def dump(self):
return self.view
Now you can dump each related object into mydict()
with
if type(v) == ReverseManyToOneDescriptor:
print(k)
mydict[k] = [instance.dump() for instance in getattr(self, k).all()]
Answered By - Chris Curvey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.