Django Rest Framework I can't use Serializer save model of have foreign key

Django Rest Framework I can't use Serializer save model of have foreign key

By : Adam Deng
Date : November 21 2020, 04:01 AM
will help you You need to serialize the Company instance before you can include it in your StageSerializer.
A simple example would be something like
code :
class CompanySerializer(ModelSerializer):

class Meta:
    model = Company
    fields = '__all__'
class StageSerializer(ModelSerializer):
    stage_id = IntegerField(read_only=True)
    company = CompanySerializer(source='company', read_only=True)
    class Meta:
        model = Stage
        fields = [

Share : facebook icon twitter icon
django rest framework foreign key serializer issue

django rest framework foreign key serializer issue

By : sylviaa
Date : March 29 2020, 07:55 AM
I hope this helps you . use serializers.SerializerMethodField to get manager name like below..
code :
class PostSerializer(serializers.ModelSerializer):
    managername = serializers.SerializerMethodField('get_manager_name')

    class Meta:
        model = tbl_dcs
        fields = ('id', 'name','location','address','managerid','phonenumber','managername')

    def get_manager_name(self, obj):
        return obj.managerid.managername
Django-rest-framework serializer fails to save model instance

Django-rest-framework serializer fails to save model instance

By : fagad
Date : March 29 2020, 07:55 AM
wish of those help I am using DRF. My models.py: , Change this in views.py
code :
data = {"farmer": request.user.id}
serializer = FarmSerializer(data=data)
data = JSONParser().parse(request)
data.update({"farmer": request.user.id})
serializer = FarmSerializer(data=data)
Django rest framework serializer foreign key

Django rest framework serializer foreign key

By : user2050200
Date : March 29 2020, 07:55 AM
this one helps. The easiest way to generate nested representations is by using depth option inside the Meta class.
code :
class EcoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ecole
        depth = 1
        fields = ('id', 'nomEcole', 'numTel', 'coordonnee')
        "coordonnee": [
                "id": 1,
                "latitude": 0,
                "longitude": 0
Django/Django Rest Framework - How do I allow model serializer to set model's foreign key field to null?

Django/Django Rest Framework - How do I allow model serializer to set model's foreign key field to null?

By : Kabir Zubaer
Date : March 29 2020, 07:55 AM
wish helps you From the docs:
code :
class AssetSerializer(serializers.ModelSerializer):
    borrower = BorrowerSerializer(allow_null=True)

    class Meta:
        model = Asset
        fields = (...)

    def update(self, instance, validated_data):
        instance.borrower = validated_data.get('borrower')

        return instance
Use serializer of model having foreign key to do CRUD on parent table in Django Rest Framework

Use serializer of model having foreign key to do CRUD on parent table in Django Rest Framework

By : user3058766
Date : March 29 2020, 07:55 AM
will help you In models I added related_name='options' in foreign key field of Option model
code :
class Question(models.Model):
    body = models.TextField()

class Options(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='options')
    option = models.CharField(max_length=100)
    is_correct = models.SmallIntegerField()
class OptionSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(required=False)

    class Meta:
        model = Option
        fields = ('id', 'question', 'option', 'is_correct')

class QuestionReadSerializer(serializers.ModelSerializer):
    options = OptionSerializer(many=True, read_only=True)

    class Meta:
        model = Question
        fields = ('id', 'body', 'options')

class QuestionWriteSerializers(serializers.ModelSerializer):
    options = OptionSerializer(many=True)

    class Meta:
        model = Question
        fields = ('id', 'body', 'options')

    def create(self, validated_data):
        options_data = validated_data.pop('options')
        question_created = Questions.objects.update_or_create(**validated_data)

        option_query = Options.objects.filter(question=question_created[0])
        if len(option_query) > 1:
            for existeding_option in option_query:

        for option_data in options_data:
            Options.objects.create(question=question_created[0], **option_data)

        return question_created[0]

    def update(self, instance, validated_data):
        options = validated_data.pop('options')
        instance.body = validated_data.get('body', instance.body)

        keep_options = []
        for option_data in options:
            if 'id' in option_data.keys():
                if Options.objects.filter(id=option_data['id'], question_id=instance.id).exists():
                    o = Options.objects.get(id=option_data['id'])
                    o.option = option_data.get('option', o.option)
                    o.is_correct = option_data.get('is_correct', o.is_correct)
                o = Options.objects.create(**option_data, question=instance)

        for option_data in instance.options.all():
            if option_data.id not in keep_options:

        return instance
class QuestionViewSet(ModelViewSet):
    queryset = Question.objects.all()

    def get_serializer_class(self) or self.request.method == 'PUT' or self.request.method == 'PATCH':
        if self.request.method == 'POST':
            return QuestionWriteSerializer
        return QuestionReadSerializer

    def create(self, request, *args, **kwargs):
        Overriding create() method to change response format
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            headers = self.get_success_headers(serializer.data)
            return Response({
                'message': 'Successfully created question',
                'data': serializer.data,
                'status': 'HTTP_201_CREATED',
            }, status=status.HTTP_201_CREATED, headers=headers)
            return Response({
                'message': 'Can not create',
                'data': serializer.errors,
                'status': 'HT',
            }, status=status.HTTP_400_BAD_REQUEST)
Related Posts Related Posts :
  • Decompose string of different symbols in python
  • pandas merge and group concat
  • How to traverse tree for making binary code from a HuffmanTree?
  • Check if IP is in network on Python3
  • non equally spaced points along x-axis in a plot
  • Concatenation of text files consisting list of lists?
  • Use regex to parse characters on a line of text
  • pandas df.fillna - filling NaNs after outer join with correct values
  • How can I undo a time series conversion of a pandas dataframe?
  • Virtual environment is not working in Django
  • FileNotFoundError in Python during Arabic text analysis
  • How to read email using python and smtplib
  • How to write a function which takes a string and turns into a single digit?
  • Linear Regression without Least Squares in sklearn
  • Matplotlib - Box plot with number of occurrence of data?
  • Finding the numbers in a given range who have a perfect square for the sum of their divisors and returning them with the
  • How do I put y(a) and y(b) initial conditions in odeint(python) instead of y(0) and y'(0)?
  • Import Error in Tensorflow in Jupyter Notebook
  • How to convert a mapping of ranges into a dictionary
  • lxml scraping overwrite error due to missing element
  • How can I run different codes from different editor tabs on the Spyder on the same console (as opposed to different tabs
  • urllib3 connectionpool - Connection pool is full, discarding connection
  • How to change django-filter filtering key?
  • Python Google Sheets API Limit 429 Error with Loop
  • How can I turn this DataFrame into a DataFrame with average score by Index Value?
  • summing element in a range for all element in an array
  • pm2 json file format for python script
  • Mask dataframe column based on datetime index
  • Brute force stable marriage, How to implements all possible pairs between 2 lists?
  • Rounding hours of datetime in PySpark
  • Show data only from one cluster
  • ValueError: Cannot feed value of shape (64,) for Tensor 'x:0', which has shape '(?, 128, 128, 1)'
  • Python try except not working with np.arccos
  • Grouping by and Combining the Strings
  • python threading.local() in different module
  • Or keyword for pandas series
  • Python Django using wsgi.py with apache2 loads filter fields out of order every restart
  • Using FireStore in Google Dataflow
  • Filter a DataFrame By Date One Week Previous From Current Date
  • How to transpose pandas dataframe to cross-tabulate dataframe keeping all values
  • How best way to transform one list into new list with pairs of elements from list?
  • Conditionals in numpy. How can i put 3 or more into my dataframe using pandas or numpy?
  • Failed to specific gcc version when setup python
  • LSTM hyperparameters not available in model.summary() after loading model
  • creating pandas-vectorized 'subtraction' table
  • Python configuration in Windows - Module locations - pip vs Eclipse/Liclipse
  • CUDA_ERROR_INVALID DEVICE with keras=2.0.5 and tensorflow-gpu=1.2.1
  • Is it safe to use next within a for loop in Python?
  • PORTING usage of s3curl.pl to Python
  • How to install Python 3.5.5?
  • Python 3.7 - PIP upgrade error on windows 10
  • How can I fix this function?
  • Optimizing execution time for appending data (Python)
  • Why my Depth function returns the Height of Binary tree not the depth?
  • How to access values of a class from a different method(out the class)
  • Groupby to create new columns
  • Fabric - ThreadingGroup exception stops remaining requests?
  • Timezone conversion with pyspark from timestamp and country
  • I want to create a table and select the value using row and column using python
  • Extract data from a span with BeautifulSoup
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org