Modelmommy class library and how to use in Python
Modelmommy is a Python library to help quickly create model instances during testing and development.It provides a simplified method to generate test data for use in unit testing, integrated testing and functional testing.
The use of modelmommy is as follows:
1. Install the ModelmomMy Library:
You can use the PIP command to install the Modelmommy library: `PIP Install Model_mommy`
2. Import the Modelmommy library:
In the Python script, you need to import the Modelmommy library to use the Modelmommy function in your test file.Use the following statement to import the Modelmommy library:
python
from model_mommy import mommy
3. Create a model instance:
Modelmommy allows you to use a line of code to create a model.You can use the method of `Mommy.make ()` to create an instance, as shown below:
python
instance = mommy.make(MyModel)
This will create an instance of a MyModel model and assign it to the `Instance` variable.
4. Custom model field:
You can customize the field of the model as needed.You can use the parameters of the field to define your value in the method of the `Make ()" method, as shown below:
python
instance = mommy.make(MyModel, field1="value1", field2="value2")
This will create an instance of a MyModel model, and set the value of the `Field1` field to` Value1 "`, and the value of the `Field2` field to" Value2 "`.
5. Create multiple model instances:
If you need to create multiple instances, you can use the second parameter of the `Make ()" method to specify the number of instances to be created.As follows:
python
instances = mommy.make(MyModel, _quantity=5)
This will create examples of 5 MyModel models and assign them to the `Instances` list.
6. Automatically fill the external key association:
If your model contains an external key association field, Modelmommy will automatically create related examples.As follows:
python
instance = mommy.make(MyModel, foreign_key_field=mommy.make(RelatedModel))
This will create an instance of a MyModel model and set its associated `Foreign_key_field` field to an instance of a RelatedModel model.
The above is the basic use of the Modelmommy library.You can use Modelmommy to create model instances according to your needs, and use these instances during the test.