Django: Custom ForeignKey - python

I'm working on a payment processor (in django 1.7) and I'm having trouble with these 2 models: Transaction and Event. They are in a custom many2one relationship in the sense that the field reference is unique in Transaction and Event entries having the same reference field belong to the Transaction with that reference. I was wondering if there a clean way to represent this in django.
I removed the reference field from the Event model, and added this transaction field:
transaction = models.ForeignKey('Transaction',db_column='reference',
to_field='reference',db_constraint=False, related_query_name='events')
This way I was able to access the transaction object from the event and use it nicely in queries, but now I can't access the reference field form an Event instance. This is weird since with a normal ForeignKey you're able to use both object and object_id.
Also I had to fake out the generated migration:(.
Is there a clean way to this?

Related

executing django model query?

In django model query, i want to know the sequential execution of it. Consider a query Blog.objects.get(name='palm').
In this where the Blog is defined, is that same as class blog in models.py?
What is objects i can't find anything related to this in source files of django. If Blog is a class, then what is the type of objects?
I want a development side concept. Can any one please explain how django makes these possible?
Every non-abstract Django model class has an attribute objects attached to it (unless you of course explicitly remove it).
object is a Manager. It is an object that has a lot of methods to construct queries that are then send to the database to fetch/store data.
So you first access the objects manager of the Blog class, next you call .get(name='palm') on it. This means that Django will translate this into a query. This depends on the database system you use. For instance if it is MySQL it will look like:
SELECT name, some, other columns
FROM app_blog
WHERE name = 'palm'
The database will respond with zero, one or more rows, and Django will, in case no or more than one row is found, raise a DoesNotExists or MultipleObjectsReturned error. Otherwise it will load the data into a Blog object (by deserializing the columns into Python objects).

Simple REST API not based on a particular predefined model

Well, I do my first steps with Django and Django REST framework. The problem I face is that all examples throughout the whole Internet are based on hard-coded models. But the whole concept of models frustrates me a little bit, because I'm used to deal with different data which comes from numerous sources (various relational databases and nosql - all that stuff). So, I do not want to stick to a particular model with a fixed number of predefined fields, but I want to specify them just at the moment when a user goes to a particular page of my app.
Let's say I have a table or a collection in one of my databases, which stores information about users - it has any kinds of fields (not just email, name and likewise - all those fields as in all those examples throughout the web). So when a user goes to /users/ I connect to my datebase, get my table, set my cursor and populate my resultant dictionary with all rows and all fields I need. And REST API does all the rest.
So, I need a "first-step" example wich starts from data, not from a model: you have a table "items" in your favorite database, when a user goes to /items/, he or she gets all data from that table. To make such simplistic api, you should do this and this... I need this kind of example.
I think the key is to use the models differently. If you use onetomany or foreignkey references in your model construction you can more dynamically link different types of data together, then access that from the parent object.
For example, for your user, you could create a basic user model and reference that in many other models such as interests, occupation, and have those models store very dynamic data.
When you have the root user model object, you can access it's foreign key objects by either iterating through the dictionary of fields returned by the object or accessing the foreign key references directly with model.reference_set.all()

What *exactly* is the relationship with the models when using ForeignKey or ManyToMany

There is something that is tripping me up with models, and I guess SQL tables in general.
Let us suppose you have these models:
class Manufacturer(models.Model):
name = models.CharField()
company_created = models.CharField()
class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer)
When you create an instance of Car like say, the following
civic = Car(manufacturer='honda')
A couple questions:
When you create an instance of Car, are you also creating an instance of Manufacturer as a by-product? Or does 'honda' need to exist as an instance already. If not, is there a way to make an instance of both, in say, one form.
Can I make calls on 'civic' for things pertaining to the manufacture? For example, could I get the 'company_created' data from the civic instance? If not, why bother having the relationship in the first place?
Thanks so much in advance. I would really appreciate a thorough answer so I can understand models and relationships fully. And yes, I have read the docs.
Firstly, the thing to remember is that these classes are representations of underlying database tables. A ForeignKey field in a Django model represents a one-to-many relationship in the database, with an _id field representing the ID of another table. Those tables are themselves independent, but are linked via the FK field (and the relevant index constraint, if the database supports them).
That said, in your Car model manufacturer is a required field (because you haven't defined it as null=True). So when you create a Car, you must point it at an already existing Manufacturer - and that manufacturer must have been saved already, so that Django can populate the underlying manufacturer_id field with the ID of the related object
Because Django is aware of the foreign key relationship between the two objects, you can use them when querying. In SQL this would be done via JOINs: Django gives you a special syntax to do queries across those joins, via double underscores. So, for example, if you wanted to get all the cars made by a manufacturer created in 1990 (assuming that's what you mean by the company_created field), you would do this:
Car.objects.filter(manufacturer__company_created='1990')
Django translates this into something like":
SELECT * from car JOIN manufacturer ON car.manufacturer_id=manufacturer.id WHERE manufacturer.company_created='1990';
If you already have your "civic" instance and just want to get access to the related data, this is pure Python object access: civic.manufacturer is the related Manufacturer object, so you can simply do civic.manufacturer.company_created to get the relevant data. Again, Django translates that into the database access, but from your point of view this is simple object composition.
Note that really all this is fully explained in the tutorial, with relationships between Poll and Choice which exactly match your Manufacturer and Car models.
Yes manufacturer need to exist as an instance already.
you can create car instance like this:
manuf= Manufacturer(name='honda',company_created='Benz')
manuf.save()
civic = Car(manufacturer=manuf)
you can get the company_created data from the civic instance by:
civic.manufacturer.company_created

How does Django handle foreignKeys internally?

I am curious how Django handles model relationships at the object level because I am working on building a custom json serializer, and I need to understand this so I have properly handle nested serialization. I am almost positive I will have to dive into some of the internals of python, but that will not be too big of a deal.
The field name in the model has _id appended to it in the table, and it stores the PK of the foreign model (as a FK normally would).
When the related field is accessed on a model, Django performs a query to retrieve the foreign model from the database.
When a model is assigned to the related field, Django reads the PK of the model and assigns it to the backing field in the table.

Django admin - Create a complex filter on User model

I have a field Foo with a ForeignKey that points to User. I need to create filter in the admin that only displays User that have at least one Foo. This would be easy with the development version of Django, but I am stuck with the 1.3.
I have seen here how to add a custom filter using the undocumented FilterSpec class. My problem is that it requires to modify the User model. I could inherit from User, but I already ave a setup where additional data is put into a Profile model wiith a one-to.one link to User.
Is there a less intrusive way to add a custom filter to the User model?
You can actually use the foreign key relation backwards in an ORM query.
User.objects.filter(foo__isnull=False)

Categories

Resources