Scott's Recipes Logo

Django versus Rails 03 - Working with the Django ORM versus ActiveRecord

Python’s Django ORM – which I think is SQL Alchemy but I really don’t know – is quite different from ActiveRecord. Here I’ll impart some practical advice:

Getting the Fields of a Class

You can use ClassName._meta.get_fields() to get information like this:

SourceClubProduct._meta.get_fields()
(<ManyToOneRel: manager.customertosourceclubproduct>, 
<ManyToOneRel: manager.pricinganalysisoutput>, 
<django.db.models.fields.BigAutoField: id>,
 <django.db.models.fields.DateTimeField: created_at>, 
<django.db.models.fields.DateTimeField: updated_at>, 
<django.db.models.fields.DateTimeField: deleted_at>, 
<django.db.models.fields.CharField: sku>, 
<django.db.models.fields.CharField: supplier_name>, 
<django.db.models.fields.DecimalField: price>)

Alas, env in the shell_plus, it will NOT be as nicely formatted as above.

Getting The First Instance of a Class

You can get the first instance of a class with this:

SourceClubProduct.objects.first()

If you wanted the sku attribute then use:

SourceClubProduct.objects.first().sku

Note: Since there are no () then it is an attribute NOT a method call.

Getting the Number of Rows from a Query

Use the len() call:

len(SourceClubProduct.objects.filter(sku=row['Sku']))
1

Alternatively you can call .count() on the queryset itself:

existing_records = SourceClubProduct.objects.filter(sku=row['Sku'])
existing_records.count()