Models Inc Dvd

0 views
Skip to first unread message

Demeter Exekutor

unread,
Aug 4, 2024, 10:39:25 PM8/4/24
to linkhcapinwei
Modelsare where your developers spend most of their time within a dbt environment. Models are primarily written as a select statement and saved as a .sql file. While the definition is straightforward, the complexity of the execution will vary from environment to environment. Models will be written and rewritten as needs evolve and your organization finds new ways to maximize efficiency.

The top level of a dbt workflow is the project. A project is a directory of a .yml file (the project configuration) and either .sql or .py files (the models). The project file tells dbt the project context, and the models let dbt know how to build a specific data set. For more details on projects, refer to About dbt projects.


Learn more about models in SQL models and Python models pages. If you'd like to begin with a bit of practice, visit our Getting Started Guide for instructions on setting up the Jaffle_Shop sample data so you can get hands-on with the power of dbt.


For example, if the models for your application live in the modulemyapp.models (the package structure that is created for anapplication by the manage.py startapp script),INSTALLED_APPS should read, in part:


Each field takes a certain set of field-specific arguments (documented in themodel field reference). For example,CharField (and its subclasses) require amax_length argument which specifies the sizeof the VARCHAR database field used to store the data.


Note that this is different than null.null is purely database-related, whereasblank is validation-related. If a field hasblank=True, form validation willallow entry of an empty value. If a field has blank=False, the field will be required.


A sequence of 2-value tuples, a mapping, anenumeration type, or a callable (thatexpects no arguments and returns any of the previous formats), to use aschoices for this field. If this is given, the default form widget will be aselect box instead of the standard text field and will limit choices to thechoices given.


Clearly, the power of relational databases lies in relating tables to eachother. Django offers ways to define the three most common types of databaserelationships: many-to-one, many-to-many and one-to-one.


For example, consider the case of an application tracking the musical groupswhich musicians belong to. There is a many-to-many relationship between a personand the groups of which they are a member, so you could use aManyToManyField to represent this relationship.However, there is a lot of detail about the membership that you might want tocollect, such as the date at which the person joined the group.


For these situations, Django allows you to specify the model that will be usedto govern the many-to-many relationship. You can then put extra fields on theintermediate model. The intermediate model is associated with theManyToManyField using thethrough argument to point to the modelthat will act as an intermediary. For our musician example, the code would looksomething like this:


When you set up the intermediary model, you explicitly specify foreignkeys to the models that are involved in the many-to-many relationship. Thisexplicit declaration defines how the two models are related.


If the custom through table defined by the intermediate model does not enforceuniqueness on the (model1, model2) pair, allowing multiple values, theremove() call willremove all intermediate model instances:


SQL reserved words, such as join, where or select, are allowed asmodel field names, because Django escapes all database table names and columnnames in every underlying SQL query. It uses the quoting syntax of yourparticular database engine.


If one of the existing model fields cannot be used to fit your purposes, or ifyou wish to take advantage of some less common database column types, you cancreate your own field class. Full coverage of creating your own fields isprovided in How to create custom model fields.


If you wish to update a field value in the save() method, you mayalso want to have this field added to the update_fields keyword argument.This will ensure the field is saved when update_fields is specified. Forexample:


Note that the delete() method for an object is notnecessarily called when deleting objects in bulk using aQuerySet or as a result of a cascadingdelete. To ensure customizeddelete logic gets executed, you can usepre_delete and/orpost_delete signals.


Model inheritance in Django works almost identically to the way normalclass inheritance works in Python, but the basics at the beginning of the pageshould still be followed. That means the base class should subclassdjango.db.models.Model.


The only decision you have to make is whether you want the parent models to bemodels in their own right (with their own database tables), or if the parentsare just holders of common information that will only be visible through thechild models.


Abstract base classes are useful when you want to put some commoninformation into a number of other models. You write your base classand put abstract=True in the Metaclass. This model will then not be used to create any databasetable. Instead, when it is used as a base class for other models, itsfields will be added to those of the child class.


The Student model will have three fields: name, age andhome_group. The CommonInfo model cannot be used as a normal Djangomodel, since it is an abstract base class. It does not generate a databasetable or have a manager, and cannot be instantiated or saved directly.


For many uses, this type of model inheritance will be exactly what you want.It provides a way to factor out common information at the Python level, whilestill only creating one database table per child model at the database level.


Due to the way Python inheritance works, if a child class inherits frommultiple abstract base classes, only the Meta optionsfrom the first listed class will be inherited by default. To inherit Meta options from multiple abstract base classes, you mustexplicitly declare the Meta inheritance. For example:


If you are using related_name orrelated_query_name on a ForeignKey orManyToManyField, you must always specify a unique reverse name and queryname for the field. This would normally cause a problem in abstract baseclasses, since the fields on this class are included into each of the childclasses, with exactly the same values for the attributes (includingrelated_name andrelated_query_name) each time.


The second type of model inheritance supported by Django is when each model inthe hierarchy is a model all by itself. Each model corresponds to its owndatabase table and can be queried and created individually. The inheritancerelationship introduces links between the child model and each of its parents(via an automatically-created OneToOneField).For example:


However, if p in the above example was not a Restaurant (it had beencreated directly as a Place object or was the parent of some other class),referring to p.restaurant would raise a Restaurant.DoesNotExistexception.


As mentioned, Django will automatically create aOneToOneField linking your childclass back to any non-abstract parent models. If you want to control thename of the attribute linking back to the parent, you can create yourown OneToOneField and setparent_link=Trueto indicate that your field is the link back to the parent class.


This is what proxy model inheritance is for: creating a proxy for theoriginal model. You can create, delete and update instances of the proxy modeland all the data will be saved as if you were using the original (non-proxied)model. The difference is that you can change things like the default modelordering or the default manager in the proxy, without having to alter theoriginal.


You could also use a proxy model to define a different default ordering ona model. You might not always want to order the Person model, but regularlyorder by the last_name attribute when you use the proxy:


There is no way to have Django return, say, a MyPerson object whenever youquery for Person objects. A queryset for Person objects will returnthose types of objects. The whole point of proxy objects is that code relyingon the original Person will use those and your own code can use theextensions you included (that no other code is relying on anyway). It is nota way to replace the Person (or any other) model everywhere with somethingof your own creation.


If you wanted to add a new manager to the Proxy, without replacing theexisting default, you can use the techniques described in the custommanager documentation: create a base classcontaining the new managers and inherit that after the primary base class:


With careful setting of Meta.db_table you could create an unmanaged model thatshadows an existing model and adds Python methods to it. However, that would bevery repetitive and fragile as you need to keep both copies synchronized if youmake any changes.


Or use a common ancestor to hold the AutoField. Thisrequires using an explicit OneToOneField from eachparent model to the common ancestor to avoid a clash between the fields thatare automatically generated and inherited by the child:


This restriction only applies to attributes which areField instances. Normal Python attributescan be overridden if you wish. It also only applies to the name of theattribute as Python sees it: if you are manually specifying the databasecolumn name, you can have the same column name appearing in both a child andan ancestor model for multi-table inheritance (they are columns in twodifferent database tables).


Note that because of the way fields are resolved during class definition, modelfields inherited from multiple abstract parent models are resolved in a strictdepth-first order. This contrasts with standard Python MRO, which is resolvedbreadth-first in cases of diamond shaped inheritance. This difference onlyaffects complex model hierarchies, which (as per the advice above) you shouldtry to avoid.


These principles are reflected throughout the architecture that enables Apple Intelligence, connects features and tools with specialized models, and scans inputs and outputs to provide each feature with the information needed to function responsibly.

3a8082e126
Reply all
Reply to author
Forward
0 new messages