Side Note: When posting code here, enclose the code between lines of three
backtick - ` characters. This means you’ll have a line of ```, then your code,
then another line of ```. This forces the forum software to keep your code
properly formatted. (I have taken the liberty of correcting your original posts.
Please remember to do this in the future.)
The first issue is that your many-to-many relationship between products
and Excipients
isn’t defined properly. See
Pay particular attention to the examples shown in that second page.
Second, don’t try to “over-manage” Django’s management of models unless you have a real and defined need to do so.
Is there a reason why you have managed = False
defined for both the Applications
and Excipients
models? (This seems odd to me, especially since you don’t have this on the products
model.)
In the general case, you don’t really want to use the to_field
and db_column
settings of the ForeignKey
field. It doesn’t make any sense for Excipients
, because the applno
field in Applications
is the primary key, so that’s the field that is going to be used anyway.
Having the ForeignKey field in Excipients
named applno
is both confusing and misleading. Within the context of the ORM, the applno
field is actually a reference to an instance of Applications
.
Next, since Excipients
is the “many” side of the many-to-one relationship, you can always refer to the related Applications
object through the foreign key field.
What this means is that for any instance of Excipients
, you can directly access the Applications
object through the foreign key field name.
For example, if you have:
an_excipient = Excipients.objects.get(id=1)
then the Applications
object related to an_exicipient
is access as an_excipient.applno
.
(This is where your mis-named field causes confusion. The expression an_excipient.applno
does not give you the applno
value.)
Also, as mentioned in the ManyToMany docs referenced above, all related objects through that relationship are accessible through the related manager using the related table name with the _set
suffix.
In this specific case, again with the example:
an_excipient = Excipients.objects.get(id=1)
then all related products
are accessed by
an_excipient.product_set.all()
Finally, you generally want to avoid using the values
functions, again unless you have a specific need for it. It becomes a limiting factor within your views and templates.