I am a Django dev and I’m stuck with a problem of reverse foreignkey lookup. The problem is described as follows:
I am working on query optimization. I have a model MicroMessage which has a foreignkey to User (from django.contrib.auth.models) as author. Also there are some other classes which have also foreignkey to User (e.g UserProfile).
I need a query which will fetch author of MicroMessage as well as all users related to any other model from which I can access the UserProfile info of that author without any excessive queries. I tried this:
MicroMessage.objects.select_reverse({'authors':'author_set'})
Please assist me. Thanks in advance.
You're looking for select_related
https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related
messages = MicroMessage.objects.select_related('author', 'author__userprofile')
The second field (a user's profile) is a reverse foreign key but if implemented as a OneToOneField as the docs suggest, can be queried in the manner shown above if the class was named UserProfile.
Related
I'm using Django, is there a way to apply foreign key and ChartField to one field at the same time? Sometimes I want to allow the user to enter a value that is not in the foreign key. I've googled for a long time and found various ways, but I can't find a solution. Please help.
[models.py]
class Supporting(models.Model):
assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, blank=False, null=True)
Foreign key only allows ids or objects of models that it has relation with. it can never ever accept text. if you want to this field to be a foreign key for other models too then there is a solution. you can use generic foreign key
You Might be looking for a through Model between Supporting and Assignment.
As per your question, you might require multiple fields defining the nature of relation between two models and Through Models are exactly made for that!
Django Through Models Docs
You can't add ForeignKey and text in Django to a single field. You have to create a foreign key (Assignment) object, and then, after a page refresh, you can attach it to the current model.
I the page refresh is not needed, AJAX has to be used.
I know I should be able to find this in the Django documentation but I was having a difficult time. In my application I need to query the default Django User model but I need to do it in a way that it will only ever return one result. For this to happen one of the fields need to be unique.
Does the Django User Model have any unique fields I can use?
Thanks.
Of course it does: username must be unique, otherwise there would be no way of logging in a specific user.
And, as agconti points out, all models have a pk field which must be unique by deifnition.
Using the Django REST Framework.
I have a many2many field in one of my models i.e.
attribute_answers = models.ManyToManyField(AttributeAnswers)
This creates its only table hence I don't have mapped in my models.
However, I want the API to allow a POST to this table, but it does not exist in models so in view and Serialize.py I cannot reference it. What is the recommendation for this?
This creates it's only table hence I don't have mapped in my models.
I assume you're talking about the reverse relationship, as attribute_answers will be accessible from the model instance that it's defined on, and will create an appropriate default serializer field.
For the reverse relationship, make sure you set the related_name on the model field, so that you can access the reverse relationship from the AttributeAnswers model.
See here: http://django-rest-framework.org/api-guide/relations.html#reverse-relations
I have two django models that are connected by a OneToOne relationship and I am having trouble seeing how to connect them in a Tastypie ModelResource.
Instead of posting some new models I will borrow the models defined in Including child resources in a Django Tastypie API to show where I am not getting how to do this. Using the Ticket and TicketComment models, imagine that the TicketComment was like this:
class TicketComment(models.Model):
ticket = models.OneToOneField('Ticket')
instead of using the ForeignKey field. I have seen the docs as well as posts like the above which are using the ToManyField and ToOneField. But that doesn't appear to work in my situation since the Ticket does not reference the TicketComment. What I want to do is be able to create an API that lists the TicketComment in the Ticket. Tastypie rightly throws an exception saying that TicketComment fields don't exist in the Ticket model. Is there a way to get the nice serialized TicketComment into the Ticket API?
There is an attribute arg that tells tastypie what field it should use. Ticket is referenced TicketComment by reverse relation. By default it will be a lowercased model name so in your example it will be ticketcomment. But i recommend you to set a related_name attribute in your model explicitly so you will know how it will be connected.
So in your tastypie you should do this :
class TicketResource(ModelResource):
comment = fields.OneToOneField('TicketCommentResource', 'ticketcomment')
And it will work fine. The second arg in OneToOneField is a attribute.
I'm trying to figure out how to get the django admin system to display my models as inlines, when there isn't a direct FK from child to parent model.
I have three models (pseudo code):
class CampaignMain(models.model):
...
class CampaignMonitor(models.model):
campaign = models.OneToOneField(CampaignMain, pk=True)
class CampaignTransaction(models.model):
campaign = models.ForeignKey(CampaignMain)
So both CampaignMonitor and CampaignTransaction FK CampaignMain, which is the way I need it to be structured.
Here's the bit I can't fathom: I need an admin page showing CampaignMonitor with CampaignTransaction as inlines. But when I try this, I get "error no fk in CampaignTransaction pointing to CampaignMonitor"
Is there a way to "force" the relationship just for the admin page? Or is there a generic FK option? I saw something in contrib/contenttypes, but it doesn't seem to be what I need. Or am I going to have to build a custom admin section to two models in that way?
As always advice is greatly appreciated.
imanc
Instead of OneToOneField you can use Multi-table inheritance, which implemented using a one-to-one relationshinp:
class CampaignMonitor(CampaignMain):
...
Now modify CampaignMonitor's admin as needed for your needs.